C#中,对于Dictionary字典类型,使用引用类型做Key的注意事项

今天,同事问了这么个问题:

为什么无法查找到字典变量中的指定Key的Value?

经过几番询问,才发现,他定义了一个int数组,来作为Dictionary的Key的类型,然后string作为DIctionary的Value。

这还真是个清奇的使用方式,我这做了五六年的C#开发,还真是从来没有这么使用过Dictionary。

毫无疑问,用int数组来当做Dictionary的Key并不是不可以,只不过有一个需要注意的地方:

int数组属于引用类型,引用类型相互比较的是引用地址,很显然用作Dictionary的Key,在不做任何措施的情况下,是找不到相同内容的Key的。

这个时候,就需要对引用类型做一下处理了:重写Equals()方法,以及重写GetHashCode()方法

下面,就是针对同事遇到的问题,稍微做了一下改进后的代码:

    public class ArrayExtend
    {
        int[] arr;
        string content = "";

        public void Init(int[] a)
        {
            int count = a.Count();
            arr = new int[count];
            for (int i = 0; i < count; i++)
            {
                arr[i] = a[i];
                content += arr[i] + ",";
            }
        }

        public override bool Equals(object obj)
        {
            ArrayExtend temp22 = (ArrayExtend)obj;
            bool flag = true;
            for (int i = 0; i < arr.Count(); i++)
            {
                if (arr[i] != temp22.arr[i])
                    flag = false;
            }
            return flag;
        }

        public override int GetHashCode()
        {
            return content.GetHashCode();
        }
    }

        private void button1_Click(object sender, EventArgs e)
        {
            Dictionary<ArrayExtend, string> dic = new Dictionary<ArrayExtend, string>();
            ArrayExtend q1 = new ArrayExtend();
            ArrayExtend q2 = new ArrayExtend();
            ArrayExtend q3 = new ArrayExtend();
            q1.Init(new int[] { 1, 2, 3, 4 });
            q2.Init(new int[] { 1, 2, 3, 4, 5 });
            q3.Init(new int[] { 1, 2, 3, 4, 5, 6 });
            int tt1 = q1.GetHashCode();
            int tt2 = q2.GetHashCode();
            int tt3 = q3.GetHashCode();
            dic.Add(q1, "Hello");
            dic.Add(q2, "World");
            dic.Add(q3, "Tom");
            ArrayExtend q4 = new ArrayExtend();
            q4.Init(new int[] { 1, 2, 3, 4, 5 });
            string str = dic[q4];
            MessageBox.Show(str);
        }

 

posted on 2022-06-24 10:18  双子双星  阅读(1614)  评论(0编辑  收藏  举报

导航