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의 상대 값을 나타내는 부호 있는 정수입니다.

의미
0보다 작음xy보다 작은 경우
0xy와 같습니다.
0보다 큼xy보다 큰 경우

예제

다음 예제에서는 인터페이스를 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이 아닌 참조보다 작은 것으로 간주됩니다.

적용 대상

추가 정보