understand equal and gethashcode

1459 ワード

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