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