您的位置:首页 > 产品设计 > UI/UE

使用结构struct作为Dictionary<TKey,TValue>的键

2014-07-22 12:56 225 查看
我们经常用简单数据类型,比如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的博文,在这里
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐