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

public:
 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

参数

x

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

y

要比较的第二个对象。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);
        }
        else
        {
            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)
		Else
			Return 0
		End If
	End Function

End Class

注解

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

继承者说明

比较null与任何引用类型允许和不会生成异常。Comparing null with any reference type is allowed and does not generate an exception. Null 引用被视为小于任何不为 null 的引用。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.

适用于

另请参阅