C# dictionary 自定义类型的containkey 方法实现

官方手册:https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.dictionary-2?view=netframework-4.7.2

 官方解决实例:

using System;
using System.Collections.Generic;

class Example
{
   static void Main()
   {
      BoxEqualityComparer boxEqC = new BoxEqualityComparer();

      var boxes = new Dictionary<Box, string>(boxEqC);

      var redBox = new Box(4, 3, 4);
      AddBox(boxes, redBox, "red");

      var blueBox = new Box(4, 3, 4);
      AddBox(boxes, blueBox, "blue");

      var greenBox = new Box(3, 4, 3);
      AddBox(boxes, greenBox, "green");
      Console.WriteLine();

      Console.WriteLine("The dictionary contains {0} Box objects.",
                        boxes.Count);
   }

   private static void AddBox(Dictionary<Box, String> dict, Box box, String name)
   {
      try {
         dict.Add(box, name);
      }
      catch (ArgumentException e) {
         Console.WriteLine("Unable to add {0}: {1}", box, e.Message);
      }
   }
}

public class Box
{
    public Box(int h,  int l, int w)
    {
        this.Height = h;
        this.Length = l;
        this.Width = w;
    }

    public int Height { get; set; }
    public int Length { get; set; }
    public int Width { get; set; }

    public override String ToString()
    {
       return String.Format("({0}, {1}, {2})", Height, Length, Width);
    }
}

class BoxEqualityComparer : IEqualityComparer<Box>
{
    public bool Equals(Box b1, Box b2)
    {
        if (b2 == null && b1 == null)
           return true;
        else if (b1 == null || b2 == null)
           return false;
        else if(b1.Height == b2.Height && b1.Length == b2.Length
                            && b1.Width == b2.Width)
            return true;
        else
            return false;
    }

    public int GetHashCode(Box bx)
    {
        int hCode = bx.Height ^ bx.Length ^ bx.Width;
        return hCode.GetHashCode();
    }
}
// The example displays the following output:
//    Unable to add (4, 3, 4): An item with the same key has already been added.
//
//    The dictionary contains 2 Box objects.

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值