zoukankan      html  css  js  c++  java
  • 使用结构struct作为Dictionary<TKey,TValue>的键

    我们经常用简单数据类型,比如int作为泛型Dictionary<TKey,TValue>的key,但有时候我们希望自定义数据类型作为Dictionary<TKey,TValue>的key,如何做到?

    如果我们想自定义一个struct类型作为key,就必须针对该struct定义一个实现IEqualityComparer<T>接口的比较类,实现该接口的2个方法:Equals()方法和GetHashCode()方法,前者用来比较两个key是否相等,后者用来获取key的哈希值。

    模拟这样一个场景:当我们去商场购物,经常需要把随身物品存放到某个储物柜,然后拿着该储物柜的钥匙。把钥匙抽象成key,不过,稍后会定义成一个struct类型的key,把随身物品抽象成值,那么所有的储物柜就是一个Dictionary<TKey,TValue>键值对集合。

    定义一个struct类型的key,并且针对该struct定义一个比较类。

    public struct GoodsKey
        {
            private int _no;
            private int _size;
    
            public GoodsKey(int no, int size)
            {
                _no = no;
                _size = size;
            }
    
            public class EqualityComparer : IEqualityComparer<GoodsKey>
            {
    
                public bool Equals(GoodsKey x, GoodsKey y)
                {
                    return x._no == y._no && x._size == y._size;
                }
    
                public int GetHashCode(GoodsKey obj)
                {
                    return obj._no ^ obj._size;
                }
            }
        }

    随身物品抽象成如下。

    public class Goods
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }

    客户端。

    class Program
        {
            static void Main(string[] args)
            {
                Dictionary<GoodsKey, Goods> list = new Dictionary<GoodsKey, Goods>(new GoodsKey.EqualityComparer());
                GoodsKey key1 =new GoodsKey(1, 100);
                list.Add(key1,new Goods(){Id = 1, Name = "手表"});
                if (list.ContainsKey(key1))
                {
                    Console.WriteLine("此柜已经本占用~~");
                }
                else
                {
                    Console.WriteLine("此柜目前是空的~~");
                }
                Console.ReadKey();
            }
        }

    运行,输出:此柜已经本占用~~

    以上,在实例化Dictionary<GoodsKey, Goods>的时候,需要在其构造函数指明实现IEqualityComparer<GoodsKey>的比较类EqualityComparer实例。

    虽然,实现了struct类型作为Dictionary<TKey,TValue>的key。但这其中存在着一些可以避免的"装箱、拆箱",优化方案可参考Jeffrey Zhao的博文,在这里

  • 相关阅读:
    python大战机器学习——聚类和EM算法
    python大战机器学习——数据降维
    机器学习(西瓜书)——绪论
    算法设计与分析-HomeWork
    SocLib的安装
    CSS的IE6、IE7、FF兼容性写法
    CSS content内容生成技术以及应用
    js javascript:void(0) 真正含义
    Google Chrome七大新特性
    CSS中文字体对照表
  • 原文地址:https://www.cnblogs.com/darrenji/p/3860307.html
Copyright © 2011-2022 走看看