各位大侠,我写了一段代码,将自定义的MyPoint类的各个对象动态的存储到hashtable中,现在我想使用某一个对象的属性值,求各位帮帮忙。代码:
类:
class MyPoint
{
public int x;
public int y;
}
事件:
        private void button2_Click(object sender, EventArgs e)
        {
              HashTable h=new HashTable();
              MyPont p1=new myPonit();
              h.Add(1,p1);
              MyPont p2=new myPonit();
              h.Add(2,p2);
              MyPont p3=new myPonit();
              h.Add(3,p3);
              MyPont p4=new myPonit();
              h.Add(4,p4);
        }假如说我现在想去使用每一个对象的属性,怎么用hash实现?就像这样的使用
for (int i = 0; i < hash.Count; i++)
            {
                for (int j = i + 1; j < hash.Count; j++)
                {
                   //得到每两个点之间的距离
                }
            }

解决方案 »

  1.   

    for (int i = 0; i < hash.Count; i++)
    {
      for (int j = i + 1; j < hash.Count; j++)
      {
         double d = Math.Sqrt((h[i].x - h[j].x) * (h[i].x - h[j].x) + (h[i].y - h[j].y) * (h[i].y - h[j].y));
      }
    }
      

  2.   


    static void Main(string[] args)
            {
                Hashtable h = new Hashtable();
                h.Add(1, new MyPoint() { x = 1, y = 2 });
                h.Add(2, new MyPoint() { x = 3, y = 4 });
                h.Add(3, new MyPoint() { x = 5, y = 7 });
                h.Add(4, new MyPoint() { x = 8, y = 10 });
                MyPoint mp;
                foreach (object item in h.Keys)
                {
                    mp = h[item] as MyPoint;
                    Console.WriteLine("X={0} Y={1} distance={2}",mp.x,mp.y,Math.Abs(mp.x-mp.y));
                }
               
                Console.ReadLine();
            }
      

  3.   

    for (int i = 0; i < h.Count; i++)
    {
      for (int j = i + 1; j < h.Count; j++)
      {
      double d = Math.Sqrt(((h[i] as MyPoint).x - (h[j] as MyPoint).x) * ((h[i] as MyPoint).x - (h[j] as MyPoint).x) + ((h[i] as MyPoint).y - (h[j] as MyPoint).y) * ((h[i] as MyPoint).y - (h[j] as MyPoint).y));
      }
    }
      

  4.   

    我半夜爬起来就是说一句,这个代码太糟,不要照搬。
    应该把类型转换提出来
    另外使用HashTable这种弱类型的东西也很糟。