Comparer<T>.Compare(T, T) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
當在派生類別中覆寫時,會比較兩個同類型的物件,並回傳一個值,表示其中一個物件是小於、等於還是大於另一個物件。
public:
abstract int Compare(T x, T y);
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
第一個比較的對象。
- y
- T
第二個比較物件。
傳回
一個有符號整數,表示 和 x的y相對值,如下表所示。
| 價值 | 意義 |
|---|---|
| 低於零 |
x 小於 y。
|
| 零 |
x 等於 y.
|
| 大於零 |
x 大於 y。
|
實作
例外狀況
Type T 既不實作通用介面,也不實作IComparable<T>介面。IComparable
範例
以下範例定義了一個可取代預設比較器的物件比較器 Box 。 此範例是本類別更大 Comparer<T> 範例的一部分。
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;
}
}
}
type BoxLengthFirst() =
inherit Comparer<Box>()
// Compares by Length, Height, and Width.
override _.Compare(x: Box, y: Box) =
if x.Length.CompareTo y.Length <> 0 then
x.Length.CompareTo y.Length
elif x.Height.CompareTo y.Height <> 0 then
x.Height.CompareTo y.Height
elif x.Width.CompareTo y.Width <> 0 then
x.Width.CompareTo y.Width
else
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。
給實施者的注意事項
允許與任意參考型別比較 null ,且不會產生例外。 空參考被視為小於任何非空參考。
關於文化特定比較的資訊,請參閱 System.Globalization 命名空間及 全球化與在地化。