IEqualityComparer<T> IEqualityComparer<T> IEqualityComparer<T> IEqualityComparer<T> Interface

정의

개체가 같은지 비교할 수 있는 메서드를 정의합니다.Defines methods to support the comparison of objects for equality.

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

형식 매개 변수

T

비교할 개체의 형식입니다.The type of objects to compare.

파생

예제

다음 예제에서는 사용자 지정 Box 사전 컬렉션 개체입니다.The following example adds custom Box objects to a dictionary collection. Box 개체 차원을 동일한 경우 같은 것으로 간주 됩니다.The Box objects are considered equal if their dimensions are the same.

using System;
using System.Collections.Generic;

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

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

      var redBox = new Box(4, 3, 4);
      AddBox(boxes, redBox, "red");
      
      var blueBox = new Box(4, 3, 4);
      AddBox(boxes, blueBox, "blue");
      
      var greenBox = new Box(3, 4, 3);
      AddBox(boxes, greenBox, "green");
      Console.WriteLine();
      
      Console.WriteLine("The dictionary contains {0} Box objects.",
                        boxes.Count);
   }

   private static void AddBox(Dictionary<Box, String> dict, Box box, String name)
   {
      try {
         dict.Add(box, name);
      }
      catch (ArgumentException e) {
         Console.WriteLine("Unable to add {0}: {1}", box, e.Message);
      }
   }
}

public class Box
{
    public Box(int h,  int l, int w)
    {
        this.Height = h;
        this.Length = l;
        this.Width = w;
    }

    public int Height { get; set; }
    public int Length { get; set; }
    public int Width { get; set; }

    public override String ToString()
    {
       return String.Format("({0}, {1}, {2})", Height, Length, Width);
    }
}


class BoxEqualityComparer : IEqualityComparer<Box>
{
    public bool Equals(Box b1, Box b2)
    {
        if (b2 == null && b1 == null)
           return true;
        else if (b1 == null || b2 == null)
           return false;
        else if(b1.Height == b2.Height && b1.Length == b2.Length
                            && b1.Width == b2.Width)
            return true;
        else
            return false;
    }

    public int GetHashCode(Box bx)
    {
        int hCode = bx.Height ^ bx.Length ^ bx.Width;
        return hCode.GetHashCode();
    }
}
// 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.

설명

이 인터페이스는 컬렉션에 대 한 사용자 지정 된 같음 비교를 구현할을 수 있습니다.This interface allows the implementation of customized equality comparison for collections. 즉, 사용자 고유의 형식에 대 한 같음 정의 만들 수 있습니다 T를 허용 하는 컬렉션 형식을 사용 하 여 사용 하도록이 정의 지정 하 고는 IEqualityComparer<T> 제네릭 인터페이스입니다.That is, you can create your own definition of equality for type T, and specify that this definition be used with a collection type that accepts the IEqualityComparer<T> generic interface. .NET framework에서의 생성자는 Dictionary<TKey,TValue> 제네릭 컬렉션 형식을이 인터페이스를 허용 합니다.In the .NET Framework, constructors of the Dictionary<TKey,TValue> generic collection type accept this interface.

이 인터페이스의 기본 구현을 제공 합니다 Default 의 속성을 EqualityComparer<T> 제네릭 클래스입니다.A default implementation of this interface is provided by the Default property of the EqualityComparer<T> generic class. 합니다 StringComparer 클래스 구현 IEqualityComparer<T> 형식의 String합니다.The StringComparer class implements IEqualityComparer<T> of type String.

이 인터페이스는 같음 비교만 지원합니다.This interface supports only equality comparisons. 제공 하는 사용자 지정 정렬 및 순서에 대 한 비교는 IComparer<T> 제네릭 인터페이스입니다.Customization of comparisons for sorting and ordering is provided by the IComparer<T> generic interface.

파생 되는 것이 좋습니다는 EqualityComparer<T> 구현 하는 대신 클래스는 IEqualityComparer<T> 인터페이스를 EqualityComparer<T> 사용 하 여 같음을 테스트 클래스는 IEquatable<T>.Equals 메서드 대신는 Object.Equals 메서드.We recommend that you derive from the EqualityComparer<T> class instead of implementing the IEqualityComparer<T> interface, because the EqualityComparer<T> class tests for equality using the IEquatable<T>.Equals method instead of the Object.Equals method. 이 일치를 Contains, IndexOf, LastIndexOf, 및 Remove 메서드를 Dictionary<TKey,TValue> 클래스 및 기타 제네릭 컬렉션입니다.This is consistent with the Contains, IndexOf, LastIndexOf, and Remove methods of the Dictionary<TKey,TValue> class and other generic collections.

메서드

Equals(T, T) Equals(T, T) Equals(T, T) Equals(T, T)

지정한 개체가 같은지 여부를 확인합니다.Determines whether the specified objects are equal.

GetHashCode(T) GetHashCode(T) GetHashCode(T) GetHashCode(T)

지정한 개체의 해시 코드를 반환합니다.Returns a hash code for the specified object.

적용 대상

추가 정보