Comparer<T>.Compare(T, T) 方法

定義

在衍生類別中覆寫時,比較型別相同的兩個物件並傳回值,指出一個物件是小於、等於還是大於另一個物件。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
T

要比較的第一個物件。The first object to compare.

y
T

要比較的第二個物件。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

備註

執行這個方法, 以提供類型T的自訂排序次序比較。Implement 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.

適用於

另請參閱