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

定義

比較兩個物件並傳回值,指出其中一個物件為小於、等於或大於另一個物件。

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

參數

x
T

要比較的第一個物件。

y
T

要比較的第二個物件。

傳回

帶正負號的整數,表示 xy 的相對值,如下表所示。

意義
小於零x 小於 y
x等於 y
大於零x 大於 y

範例

下列範例會實作 IComparer<T> 介面,以根據其維度比較型 Box 別的物件。 這個範例是提供給 類別之較大範例的 Comparer<T> 一部分。

// 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;
        }
    }
}
' 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
    Implements IComparer(Of Box)
    ' Compares by Height, Length, and Width.
    Public Function Compare(ByVal x As Box, ByVal y As Box) As Integer Implements _
                                                IComparer(Of Box).Compare
        If x.Height.CompareTo(y.Height) <> 0 Then
            Return x.Height.CompareTo(y.Height)
        ElseIf x.Length.CompareTo(y.Length) <> 0 Then
            Return x.Length.CompareTo(y.Length)
        ElseIf x.Width.CompareTo(y.Width) <> 0 Then
            Return x.Width.CompareTo(y.Width)
        Else
            Return 0
        End If
    End Function
End Class

備註

實作這個方法,以提供類型的 T自定義排序順序比較。

null允許與任何參考型別比較,而且不會產生例外狀況。 Null 參考會被視為小於非 Null 的任何參考。

適用於

另請參閱