C#使用struct类型作为泛型Dictionary<TKey,TValue>的键

作者:Darren 时间:2023-10-09 01:53:35 

我们经常用简单数据类型,比如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实例。

来源:https://www.cnblogs.com/darrenji/p/3860307.html

标签:C#,struct,类型,泛型,Dictionary,TKey,TValue
0
投稿

猜你喜欢

  • Spring Cloud整合XXL-Job的示例代码

    2021-06-09 06:01:59
  • c# 调用Win32Api关闭当前应用的方法

    2023-09-22 20:51:26
  • Java 数据结构中二叉树前中后序遍历非递归的具体实现详解

    2023-02-14 12:51:18
  • C#中的预处理器指令详解

    2022-05-04 21:22:32
  • c#实现ini文件读写类分享

    2022-08-31 09:47:48
  • 一种类似JAVA线程池的C++线程池实现方法

    2021-11-02 21:31:52
  • 浅谈Spring中@NotEmpty、@NotBlank、@NotNull区别

    2023-01-02 08:15:49
  • Java中byte输出write到文件的实现方法讲解

    2023-12-25 11:11:36
  • Android Mms之:对话与联系人关联的总结详解

    2023-12-06 13:12:57
  • Spring AOP实现权限检查的功能

    2023-08-10 06:51:14
  • Android使用PhotoView实现图片双击放大单击退出效果

    2022-10-10 04:52:11
  • 解决Android 5.1限制外置SD卡写入权限的问题

    2021-08-05 03:54:41
  • ElasticSearch添加索引代码实例解析

    2023-11-21 03:41:04
  • Springboot 在普通类型注入Service或mapper

    2023-11-29 15:26:21
  • Java中重载与重写的对比与区别

    2021-08-29 13:22:31
  • Android 媒体库数据更新方法总结

    2022-04-24 10:22:17
  • Spring Boot @Conditional注解用法示例介绍

    2023-04-18 22:51:51
  • Java技巧函数方法实现二维数组遍历

    2023-09-12 23:25:00
  • 利用OPENCV为android开发畸变校正的JNI库方法

    2021-10-06 17:33:27
  • Android中为activity创建菜单

    2022-10-19 05:52:12
  • asp之家 软件编程 m.aspxhome.com