C#使用struct類型作為泛型Dictionary<TKey,TValue>的鍵
我們經(jīng)常用簡單數(shù)據(jù)類型,比如int作為泛型Dictionary<TKey,TValue>的key,但有時候我們希望自定義數(shù)據(jù)類型作為Dictionary<TKey,TValue>的key,如何做到?
如果我們想自定義一個struct類型作為key,就必須針對該struct定義一個實現(xiàn)IEqualityComparer<T>接口的比較類,實現(xiàn)該接口的2個方法:Equals()方法和GetHashCode()方法,前者用來比較兩個key是否相等,后者用來獲取key的哈希值。
模擬這樣一個場景:當我們?nèi)ド虉鲑徫铮?jīng)常需要把隨身物品存放到某個儲物柜,然后拿著該儲物柜的鑰匙。把鑰匙抽象成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("此柜已經(jīng)本占用~~");
}
else
{
Console.WriteLine("此柜目前是空的~~");
}
Console.ReadKey();
}
}
運行,輸出:此柜已經(jīng)本占用~~
以上,在實例化Dictionary<GoodsKey, Goods>的時候,需要在其構(gòu)造函數(shù)指明實現(xiàn)IEqualityComparer<GoodsKey>的比較類EqualityComparer實例。
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
unity實現(xiàn)鼠標經(jīng)過時ui及物體的變色操作
這篇文章主要介紹了unity實現(xiàn)鼠標經(jīng)過時ui及物體的變色操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04
unity android設(shè)備上查看log輸出方式
這篇文章主要介紹了unity android設(shè)備上查看log輸出方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-04-04
c#讀寫App.config,ConfigurationManager.AppSettings 不生效的解決方法
這篇文章主要介紹了c#讀寫App.config,ConfigurationManager.AppSettings 不生效的解決方法,需要的朋友可以參考下2015-10-10

