GetHashCode 与HashTable ,Dictionary

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Collections;
using Data = System.Data.SqlClient;

namespace COL_TEST
{
    class Program
    {
        static void Main(string[] args)
        {
            //一个对象的 GetHashCode 方法必须总是返回同一个哈希代码
            //Console.WriteLine(ht.GetHashCode());
            //Console.WriteLine(ht.GetHashCode());

            A a = new A(2, 2);
            A aa = new A(1, 4);
            A bb = new A(1, 3);
            Dictionary<A, int> hs = new Dictionary<A, int>();
            hs.Add(a, 2);
            hs.Add(aa, 2);
            hs.Add(bb, 2);

            foreach (KeyValuePair<A, int> p in hs)
            {
                Console.WriteLine("Key: " + p.Key + "   Value: " + p.Value);
                Console.WriteLine("hashCode:{0}", p.Key.GetHashCode());
            }

            Console.WriteLine("-----------------");
            /***************/
            Hashtable hht = new Hashtable();
            Class3 cc = new Class3(2, 3);
            Class3 cc2 = new Class3(1, 4);
            Class3 cc3 = new Class3(3, 3);
            hht.Add(cc, "test1");
            hht.Add(cc2, "test2");
            hht.Add(cc3, "test3");
            //cc.x = 5;  //如果修改cc的状态,会导致cc遍历不到
            foreach (var item in hht.Keys)
            {
                Console.WriteLine(item.ToString());
                Console.WriteLine(hht[item]);
            }
            Console.Read(); 

            //如果将一个引用类型的数据加入到hashTable中,首先会调用该类型的GetHashCode方法,返回的键值为重写toString 方法返回值
            //
        }
    }

    public struct MyStruct
    {

        public int _sx;
        public string _msg;

        public int _id;

        public DateTime _epoch;

    }



    class A
    {
        int i, j;
        public A(int i, int j)
        {
            this.i = i;
            this.j = j;
        }

        public override Int32 GetHashCode()
        {
            return i * j;
        }
        public override string ToString()
        {
            return String.Format("({0},{1})", i, j);
        }
    }
    class Class3
    {
        public int x;
        int y;
        public Class3(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();
        }
    }  

}

原文地址:https://www.cnblogs.com/voidobject/p/3975488.html