IEqualityComparer<T> 介面

定義

定義支援物件之相等比較的方法。

C#
public interface IEqualityComparer<in T>
C#
public interface IEqualityComparer<T>

類型參數

T

要比較之物件的類型。

這是反變數的型別參數。 也就是說,您可以使用您指定的類型,或衍生程度較低的任何類型。 如需共變數與反變數的詳細資訊,請參閱泛型中的共變數與反變數
衍生

範例

下列範例會將自定義 Box 物件新增至字典集合。 如果物件維度相同,則會 Box 將其視為相等。

C#
using System;
using System.Collections.Generic;

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

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

        AddBox(new Box(4, 3, 4), "red");
        AddBox(new Box(4, 3, 4), "blue");
        AddBox(new Box(3, 4, 3), "green");

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

        void AddBox(Box box, string name)
        {
            try
            {
                boxes.Add(box, name);
            }
            catch (ArgumentException e)
            {
                Console.WriteLine($"Unable to add {box}: {e.Message}");
            }
        }
    }
}

class Box
{
    public int Height { get; }
    public int Length { get; }
    public int Width { get; }

    public Box(int height, int length, int width)
    {
        Height = height;
        Length = length;
        Width = width;
    }

    public override string ToString() => $"({Height}, {Length}, {Width})";
}

class BoxEqualityComparer : IEqualityComparer<Box>
{
    public bool Equals(Box? b1, Box? b2)
    {
        if (ReferenceEquals(b1, b2))
            return true;

        if (b2 is null || b1 is null)
            return false;

        return b1.Height == b2.Height
            && b1.Length == b2.Length
            && b1.Width == b2.Width;
    }

    public int GetHashCode(Box box) => box.Height ^ box.Length ^ box.Width;
}

// 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.

備註

這個介面允許實作集合的自定義相等比較。 也就是說,您可以建立自己的類型 T相等定義,並指定此定義與接受泛型介面的 IEqualityComparer<T> 集合類型搭配使用。 在 .NET Framework 中,泛型集合類型的建構Dictionary<TKey,TValue>函式會接受這個介面。

這個介面的預設實作是由 Default 泛型類別的 EqualityComparer<T> 屬性所提供。 類別 StringComparer 會實作 IEqualityComparer<T> 型別 String

這個介面只支援相等比較。 自定義排序和排序的比較是由泛型介面所 IComparer<T> 提供。

我們建議您衍生自 EqualityComparer<T> 類別,而不是實 IEqualityComparer<T> 作 介面,因為 EqualityComparer<T> 類別會使用 方法來測試是否相等, IEquatable<T>.Equals 而不是 Object.Equals 方法。 這與 Contains類別和其他泛型集合的 Dictionary<TKey,TValue>IndexOfLastIndexOf、 和 Remove 方法一致。

方法

Equals(T, T)

判斷指定的物件是否相等。

GetHashCode(T)

傳回指定物件的雜湊碼。

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

另請參閱