malaikuangren

What is the purpose or drive to build thing like (xxx),How can it achieve the original goal of design?
understand equal and gethashcode

Supposed we have a class below

 

public class TestHash
    {
        public int x;
        int y;
        public TestHash(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
        public override int GetHashCode()
        {
            Console.WriteLine("判断hashcode");
            return x + y;
        }
        public override bool Equals(object obj)
        {
            Console.WriteLine("判断equals");
            return base.Equals(obj);
        }
        public override string ToString()
        {
            return x.ToString() + y.ToString();
        }
    }

  

Hashtable ht = new Hashtable();
            TestHash cc = new TestHash(2, 3);
            TestHash cc2 = new TestHash(1, 4);
            TestHash cc3 = new TestHash(3, 3);
            ht.Add(cc, "test1");
            ht.Add(cc2, "test2");
            ht.Add(cc3, "test3");
            

            Console.WriteLine("Begin print....");
            foreach (TestHash im in ht.Keys)
            {
                Console.WriteLine(im.ToString() + " -----  " + ht[im]);
            }
            Console.Read(); 

  

 

See also:

http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx

http://msdn.microsoft.com/zh-cn/library/system.object.gethashcode(v=vs.110).aspx

 

posted on 2014-03-14 16:41  malaikuangren  阅读(128)  评论(0编辑  收藏  举报