IEqualityComparer<T> 인터페이스

정의

개체가 같은지 비교할 수 있는 메서드를 정의합니다.

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

형식 매개 변수

T

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

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

예제

다음 예제에서는 사전 컬렉션에 사용자 지정 Box 개체를 추가합니다. 개체의 Box 차원이 같으면 개체는 같음으로 간주됩니다.

using System;
using System.Collections.Generic;

static class Example
{
    static void Main()
    {
        BoxEqualityComparer comparer = new();

        Dictionary<Box, string> boxes = new(comparer);

        AddBox(new Box(4, 3, 4), "red");
        AddBox(new Box(4, 3, 4), "blue");
        AddBox(new Box(3, 4, 3), "green");

        Console.WriteLine($"The dictionary contains {boxes.Count} Box objects.");

        void AddBox(Box box, string name)
        {
            try
            {
                boxes.Add(box, name);
            }
            catch (ArgumentException e)
            {
                Console.WriteLine($"Unable to add {box}: {e.Message}");
            }
        }
    }
}

class Box
{
    public int Height { get; }
    public int Length { get; }
    public int Width { get; }

    public Box(int height, int length, int width)
    {
        Height = height;
        Length = length;
        Width = width;
    }

    public override string ToString() => $"({Height}, {Length}, {Width})";
}

class BoxEqualityComparer : IEqualityComparer<Box>
{
    public bool Equals(Box? b1, Box? b2)
    {
        if (ReferenceEquals(b1, b2))
            return true;

        if (b2 is null || b1 is null)
            return false;

        return b1.Height == b2.Height
            && b1.Length == b2.Length
            && b1.Width == b2.Width;
    }

    public int GetHashCode(Box box) => box.Height ^ box.Length ^ box.Width;
}

// The example displays the following output:
//    Unable to add (4, 3, 4): An item with the same key has already been added.
//    The dictionary contains 2 Box objects.
Imports System.Collections.Generic

Module Example
   Public Sub Main()

      Dim boxEqC As New BoxEqualityComparer()

      Dim boxes As New Dictionary(Of Box, String)(boxEqC)

      Dim redBox = New Box(4, 3, 4)
      AddBox(boxes, redBox, "red")

      Dim blueBox = new Box(4, 3, 4)
      AddBox(boxes, blueBox, "blue")

      Dim greenBox = new Box(3, 4, 3)
      AddBox(boxes, greenBox, "green")
      Console.WriteLine()

      Console.WriteLine("The dictionary contains {0} Box objects.",
                        boxes.Count)
   End Sub

   Private Sub AddBox(dict As Dictionary(Of Box, String), box As Box, name As String)
      Try
         dict.Add(box, name)
      Catch e As ArgumentException
         Console.WriteLine("Unable to add {0}: {1}", box, e.Message)
      End Try
   End Sub
End Module

Public Class Box
    Private _Height As Integer
    Private _Length As Integer
    Private _Width As Integer

    Public Sub New(ByVal h As Integer, ByVal l As Integer,
                                        ByVal w As Integer)
        Me.Height = h
        Me.Length = l
        Me.Width = w
    End Sub

    Public Property Height() As Integer
        Get
            Return _Height
        End Get
        Set(ByVal value As Integer)
            _Height = value
        End Set
    End Property

    Public Property Length() As Integer
        Get
            Return _Length
        End Get
        Set(ByVal value As Integer)
            _Length = value
        End Set
    End Property

    Public Property Width() As Integer
        Get
            Return _Width
        End Get
        Set(ByVal value As Integer)
            _Width = value
        End Set
    End Property

    Public Overrides Function ToString() As String
       Return String.Format("({0}, {1}, {2})", _Height, _Length, _Width)
    End Function
End Class

Class BoxEqualityComparer
    Implements IEqualityComparer(Of Box)

    Public Overloads Function Equals(ByVal b1 As Box, ByVal b2 As Box) _
                   As Boolean Implements IEqualityComparer(Of Box).Equals

        If b1 Is Nothing AndAlso b2 Is Nothing Then
            Return True
        ElseIf b1 Is Nothing Or b2 Is Nothing Then
            Return False
        ElseIf b1.Height = b2.Height AndAlso b1.Length =
                b2.Length AndAlso b1.Width = b2.Width Then
            Return True
        Else
            Return False
        End If
    End Function

    Public Overloads Function GetHashCode(ByVal bx As Box) _
                As Integer Implements IEqualityComparer(Of Box).GetHashCode
        Dim hCode As Integer = bx.Height Xor bx.Length Xor bx.Width
        Return hCode.GetHashCode()
    End Function

End Class
' The example displays the following output:
'    Unable to add (4, 3, 4): An item with the same key has already been added.
'
'    The dictionary contains 2 Box objects.

설명

이 인터페이스를 사용하면 컬렉션에 대해 사용자 지정된 같음 비교를 구현할 수 있습니다. 즉, 형식 T에 대한 고유한 같음 정의를 만들고 이 정의를 제네릭 인터페이스를 허용하는 컬렉션 형식과 함께 사용되도록 지정할 수 있습니다 IEqualityComparer<T> . .NET Framework 제네릭 컬렉션 형식의 생성자는 이 인터페이스를 Dictionary<TKey,TValue> 허용합니다.

이 인터페이스의 기본 구현은 제네릭 클래스의 Default 속성에서 EqualityComparer<T> 제공됩니다. 클래스는 StringComparer 형식String을 구현합니다IEqualityComparer<T>.

이 인터페이스는 같음 비교만 지원합니다. 정렬 및 순서 지정에 대한 비교 사용자 지정은 제네릭 인터페이스에서 IComparer<T> 제공합니다.

클래스는 메서드 대신 메서드를 EqualityComparer<T> 사용하여 IEquatable<T>.Equals 같음을 테스트하므로 인터페이스 EqualityComparer<T> 를 구현하는 IEqualityComparer<T> 대신 클래스에서 파생하는 Object.Equals 것이 좋습니다. 이는 클래스 및 기타 제네릭 컬렉션의 Dictionary<TKey,TValue> , IndexOf, LastIndexOf및 메서드와 Remove 일치Contains합니다.

메서드

Equals(T, T)

지정한 개체가 같은지 여부를 확인합니다.

GetHashCode(T)

지정한 개체의 해시 코드를 반환합니다.

적용 대상

추가 정보