欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#使用struct類型作為泛型Dictionary<TKey,TValue>的鍵

 更新時(shí)間:2022年08月13日 14:32:22   作者:Darren Ji  
這篇文章介紹了C#使用struct類型作為泛型Dictionary<TKey,TValue>鍵值的方法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

我們經(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)文章

最新評(píng)論