當前位置: 首頁>>代碼示例>>C#>>正文


C# IEqualityComparer<T>接口代碼示例

本文整理匯總了C#中System.Collections.Generic.IEqualityComparer<T>接口的典型用法代碼示例。如果您正苦於以下問題:C# IEqualityComparer<T>接口的具體用法?C# IEqualityComparer<T>怎麽用?C# IEqualityComparer<T>使用的例子?那麽, 這裏精選的接口代碼示例或許可以為您提供幫助。


IEqualityComparer<T>接口屬於System.Collections.Generic命名空間,在下文中一共展示了IEqualityComparer<T>接口的1個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: Main

//引入命名空間
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();
    }
}
開發者ID:.NET開發者,項目名稱:System.Collections.Generic,代碼行數:77,代碼來源:IEqualityComparer

輸出:

Unable to add (4, 3, 4): An item with the same key has already been added.

The dictionary contains 2 Box objects.


注:本文中的System.Collections.Generic.IEqualityComparer<T>接口示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。