Comparer<T>.Compare(T, T) Method


在派生类中重写时,对同一类型的两个对象执行比较并返回一个值,指示一个对象是小于、等于还是大于另一个对象。When overridden in a derived class, performs a comparison of two objects of the same type and returns a value indicating whether one object is less than, equal to, or greater than the other.

 abstract int Compare(T x, T y);
public abstract int Compare (T x, T y);
abstract member Compare : 'T * 'T -> int
Public MustOverride Function Compare (x As T, y As T) As Integer



要比较的第一个对象。The first object to compare.


要比较的第二个对象。The second object to compare.



一个有符号整数,指示 xy 的相对值,如下表所示。A signed integer that indicates the relative values of x and y, as shown in the following table.

Value 含义Meaning
小于零Less than zero x 小于 yx is less than y.
Zero x 等于 yx equals y.
大于零Greater than zero x 大于 yx is greater than y.



类型 T 没有实现 IComparable<T> 泛型接口或 IComparable 接口。Type T does not implement either the IComparable<T> generic interface or the IComparable interface.


下面的示例定义了可用于代替默认比较器的 Box 对象的比较器。The following example defines a comparer of Box objects that can be used instead of the default comparer. 此示例是为 Comparer<T> 类提供的更大示例的一部分。This example is part of a larger example provided for the Comparer<T> class.

public class BoxLengthFirst : Comparer<Box>
    // Compares by Length, Height, and Width.
    public override int Compare(Box x, Box y)
        if (x.Length.CompareTo(y.Length) != 0)
            return x.Length.CompareTo(y.Length);
        else if (x.Height.CompareTo(y.Height) != 0)
            return x.Height.CompareTo(y.Height);
        else if (x.Width.CompareTo(y.Width) != 0)
            return x.Width.CompareTo(y.Width);
            return 0;
Public Class BoxLengthFirst
    Inherits Comparer(Of Box)
    ' Compares by Length, Height, and Width.
    Public Overrides Function Compare(ByVal x As Box, ByVal y As Box) As Integer
        If x.Length.CompareTo(y.Length) <> 0 Then
            Return x.Length.CompareTo(y.Length)
        ElseIf x.Height.CompareTo(y.Height) <> 0 Then
            Return x.Height.CompareTo(y.Height)
        ElseIf x.Width.CompareTo(y.Width) <> 0 Then
            Return x.Width.CompareTo(y.Width)
            Return 0
        End If
    End Function

End Class


实现此方法可以为类型 T提供自定义的排序顺序比较。Implement this method to provide a customized sort order comparison for type T.

Notes to Implementers

允许比较 null 与任何引用类型,并且不会生成异常。Comparing null with any reference type is allowed and does not generate an exception. 空引用被视为小于任何非空引用。A null reference is considered to be less than any reference that is not null.

有关区域性特定的比较信息,请参阅 System.Globalization 命名空间和全球化和本地化For information on culture-specific comparisons, see the System.Globalization namespace and Globalization and Localization.

Applies to

See also