IComparer<T>.Compare(T, T) Metodo
Definizione
Importante
Alcune informazioni sono relative alla release non definitiva del prodotto, che potrebbe subire modifiche significative prima della release definitiva. Microsoft non riconosce alcuna garanzia, espressa o implicita, in merito alle informazioni qui fornite.
Confronta due oggetti e restituisce un valore indicante se uno è minore, uguale o maggiore dell'altro.
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
Parametri
- x
- T
Primo oggetto da confrontare.
- y
- T
Secondo oggetto da confrontare.
Restituisce
Intero con segno che indica i valori relativi di x e y, come illustrato nella tabella seguente.
| Valore | Significato |
|---|---|
| Minore di zero |
x è minore di y.
|
| Zero |
x è uguale a y.
|
| Maggiore di zero |
x è maggiore di y.
|
Esempio
Nell'esempio seguente viene implementata l'interfaccia IComparer<T> per confrontare gli oggetti di tipo Box in base alle relative dimensioni. Questo esempio fa parte di un esempio più grande fornito per la Comparer<T> classe.
// 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
Commenti
Implementare questo metodo per fornire un confronto degli ordini di ordinamento personalizzato per il tipo T.
Il confronto null con qualsiasi tipo di riferimento è consentito e non genera un'eccezione. Un riferimento Null viene considerato minore di qualsiasi riferimento che non è Null.