IComparer<T> 接口

定义

定义类型为比较两个对象而实现的方法。

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

类型参数

T

要比较的对象的类型。

这是逆变类型参数。 即,可以使用指定的类型,也可以使用派生程度较低的任何类型。 有关协变和逆变的详细信息,请参阅泛型中的协变和逆变
派生

示例

以下示例实现 接口, IComparer<T> 以根据对象的尺寸比较 类型的 Box 对象。 此示例是为 类提供的更大示例的一 Comparer<T> 部分。

C#
// This class is not demonstrated in the Main method
// and is provided only to show how to implement
// the interface. It is recommended to derive
// from Comparer<T> instead of implementing IComparer<T>.
public class BoxComp : IComparer<Box>
{
    // Compares by Height, Length, and Width.
    public int Compare(Box x, Box y)
    {
        if (x.Height.CompareTo(y.Height) != 0)
        {
            return x.Height.CompareTo(y.Height);
        }
        else if (x.Length.CompareTo(y.Length) != 0)
        {
            return x.Length.CompareTo(y.Length);
        }
        else if (x.Width.CompareTo(y.Width) != 0)
        {
            return x.Width.CompareTo(y.Width);
        }
        else
        {
            return 0;
        }
    }
}

注解

此接口与 List<T>.SortList<T>.BinarySearch 方法一起使用。 它提供了一种自定义集合的排序顺序的方法。 实现此接口的类包括 SortedDictionary<TKey,TValue>SortedList<TKey,TValue> 泛型类。

此接口的默认实现是 Comparer<T> 类。 类 StringComparer 为类型 String实现此接口。

此接口支持排序比较。 也就是说,当方法返回 0 时 Compare ,这意味着两个对象排序相同。 完全相等比较的实现由 IEqualityComparer<T> 泛型接口提供。

建议派生自 Comparer<T> 类,而不是实现 IComparer<T> 接口,因为 Comparer<T> 类提供 方法的 IComparer.Compare 显式接口实现,以及 Default 获取 对象的默认比较器的属性。

方法

Compare(T, 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

另请参阅