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>IndexOfLastIndexOfRemove 方法一致。

方法

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

另请参阅