IComparer<T> 인터페이스

정의

형식에서 두 개체를 비교하기 위해 구현하는 메서드를 정의합니다.

generic <typename T>
public interface class IComparer
public interface IComparer<in T>
public interface IComparer<T>
type IComparer<'T> = interface
Public Interface IComparer(Of In T)
Public Interface IComparer(Of T)

형식 매개 변수

T

비교할 개체의 형식입니다.

이 형식 매개 변수는 반공변(Contravariant)입니다. 즉, 지정한 형식이나 더 적게 파생된 모든 형식을 사용할 수 있습니다. 공변성(Covariance) 및 반공변성(Contravariance)에 대한 자세한 내용은 제네릭의 공변성(Covariance) 및 반공변성(Contravariance)을 참조하세요.
파생

예제

다음 예제에서는 인터페이스를 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

설명

이 인터페이스는 및 메서드와 List<T>.BinarySearch 함께 List<T>.Sort 사용됩니다. 컬렉션의 정렬 순서를 사용자 지정하는 방법을 제공합니다. 이 인터페이스를 구현하는 클래스에는 및 SortedList<TKey,TValue> 제네릭 클래스가 포함 SortedDictionary<TKey,TValue> 됩니다.

이 인터페이스의 기본 구현은 클래스입니다 Comparer<T> . 클래스는 StringComparer 형식 String에 대해 이 인터페이스를 구현합니다.

이 인터페이스는 순서 비교를 지원합니다. 즉, 메서드가 0을 Compare 반환하면 두 개체가 동일한 정렬을 의미합니다. 정확한 같음 비교 구현은 제네릭 인터페이스에서 IEqualityComparer<T> 제공됩니다.

클래스는 메서드 Default 및 개체의 기본 비교자를 가져오는 속성의 명시적 인터페이스 구현을 제공하므로 인터페이스 Comparer<T> 를 구현 IComparer.Compare 하는 IComparer<T> 대신 클래스에서 Comparer<T> 파생하는 것이 좋습니다.

메서드

Compare(T, T)

두 개체를 비교하여 한 개체가 다른 개체보다 작거나, 같거나 또는 크다는 것을 나타내는 값을 반환합니다.

적용 대상

추가 정보