EqualityComparer<T> 클래스

정의

IEqualityComparer<T> 제네릭 인터페이스의 구현에 대한 기본 클래스를 제공합니다.

generic <typename T>
public ref class EqualityComparer abstract : System::Collections::Generic::IEqualityComparer<T>, System::Collections::IEqualityComparer
public abstract class EqualityComparer<T> : System.Collections.Generic.IEqualityComparer<T>, System.Collections.IEqualityComparer
[System.Serializable]
public abstract class EqualityComparer<T> : System.Collections.Generic.IEqualityComparer<T>, System.Collections.IEqualityComparer
type EqualityComparer<'T> = class
    interface IEqualityComparer<'T>
    interface IEqualityComparer
[<System.Serializable>]
type EqualityComparer<'T> = class
    interface IEqualityComparer
    interface IEqualityComparer<'T>
Public MustInherit Class EqualityComparer(Of T)
Implements IEqualityComparer, IEqualityComparer(Of T)

형식 매개 변수

T

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

상속
EqualityComparer<T>
특성
구현

예제

다음 예제에서는 같음 비교자를 사용하여 형식 Box 의 개체 사전 컬렉션을 만듭니다. 크기가 같으면 두 상자가 같은 것으로 간주됩니다. 그런 다음 컬렉션에 상자를 추가합니다.

사전은 서로 다른 방식으로 같음을 정의하는 같음 비교자를 사용하여 다시 만들어집니다. 두 상자는 볼륨이 같으면 같음으로 간주됩니다.

using System;
using System.Collections.Generic;

class Program
{
    static Dictionary<Box, String> boxes;

    static void Main()
    {
        BoxSameDimensions boxDim = new BoxSameDimensions();
        boxes = new Dictionary<Box, string>(boxDim);

        Console.WriteLine("Boxes equality by dimensions:");
        Box redBox = new Box(8, 4, 8);
        Box greenBox = new Box(8, 6, 8);
        Box blueBox = new Box(8, 4, 8);
        Box yellowBox = new Box(8, 8, 8);
        AddBox(redBox, "red");
        AddBox(greenBox, "green");
        AddBox(blueBox, "blue");
        AddBox(yellowBox, "yellow");

        Console.WriteLine();
        Console.WriteLine("Boxes equality by volume:");

        BoxSameVolume boxVolume = new BoxSameVolume();
        boxes = new Dictionary<Box, string>(boxVolume);
        Box pinkBox = new Box(8, 4, 8);
        Box orangeBox = new Box(8, 6, 8);
        Box purpleBox = new Box(4, 8, 8);
        Box brownBox = new Box(8, 8, 4);
        AddBox(pinkBox, "pink");
        AddBox(orangeBox, "orange");
        AddBox(purpleBox, "purple");
        AddBox(brownBox, "brown");
    }

    public static void AddBox(Box bx, string name)
    {
        try
        {
            boxes.Add(bx, name);
            Console.WriteLine("Added {0}, Count = {1}, HashCode = {2}",
                name, boxes.Count.ToString(), bx.GetHashCode());
        }
        catch (ArgumentException)
        {
            Console.WriteLine("A box equal to {0} is already in the collection.", name);
        }
    }
}

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; }
}

class BoxSameDimensions : EqualityComparer<Box>
{
    public override bool Equals(Box b1, Box b2)
    {
        if (b1 == null && b2 == null)
            return true;
        else if (b1 == null || b2 == null)
            return false;

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

    public override int GetHashCode(Box bx)
    {
        int hCode = bx.Height ^ bx.Length ^ bx.Width;
        return hCode.GetHashCode();
    }
}

class BoxSameVolume : EqualityComparer<Box>
{
    public override bool Equals(Box b1, Box b2)
    {
        if (b1 == null && b2 == null)
            return true;
        else if (b1 == null || b2 == null)
            return false;

        return (b1.Height * b1.Width * b1.Length ==
                b2.Height * b2.Width * b2.Length);
    }

    public override int GetHashCode(Box bx)
    {
        int hCode = bx.Height * bx.Length * bx.Width;
        return hCode.GetHashCode();
    }
}
/* This example produces an output similar to the following:
 *
      Boxes equality by dimensions:
      Added red, Count = 1, HashCode = 46104728
      Added green, Count = 2, HashCode = 12289376
      A box equal to blue is already in the collection.
      Added yellow, Count = 3, HashCode = 43495525

      Boxes equality by volume:
      Added pink, Count = 1, HashCode = 55915408
      Added orange, Count = 2, HashCode = 33476626
      A box equal to purple is already in the collection.
      A box equal to brown is already in the collection.
 *
*/
'Imports System.Collections
Imports System.Collections.Generic

Module Program
    Dim boxes As Dictionary(Of Box, [String])

    Public Sub Main(ByVal args As String())

        Dim boxDim As New BoxSameDimensions()
        boxes = New Dictionary(Of Box, String)(boxDim)

        Console.WriteLine("Boxes equality by dimensions:")
        Dim redBox As New Box(8, 4, 8)
        Dim greenBox As New Box(8, 6, 8)
        Dim blueBox As New Box(8, 4, 8)
        Dim yellowBox As New Box(8, 8, 8)
        AddBox(redBox, "red")
        AddBox(greenBox, "green")
        AddBox(blueBox, "blue")
        AddBox(yellowBox, "yellow")

        Console.WriteLine()
        Console.WriteLine("Boxes equality by volume:")

        Dim boxVolume As New BoxSameVolume()
        boxes = New Dictionary(Of Box, String)(boxVolume)
        Dim pinkBox As New Box(8, 4, 8)
        Dim orangeBox As New Box(8, 6, 8)
        Dim purpleBox As New Box(4, 8, 8)
        Dim brownBox As New Box(8, 8, 4)
        AddBox(pinkBox, "pink")
        AddBox(orangeBox, "orange")
        AddBox(purpleBox, "purple")
        AddBox(brownBox, "brown")
    End Sub

    Public Sub AddBox(ByVal bx As Box, ByVal name As String)
        Try
            boxes.Add(bx, name)
            Console.WriteLine("Added {0}, Count = {1}, HashCode = {2}", _
                              name, boxes.Count.ToString(), bx.GetHashCode())
        Catch generatedExceptionName As ArgumentException
            Console.WriteLine("A box equal to {0} is already in the collection.", name)
        End Try
    End Sub
End Module

Public Class Box
    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
    
    Private _Height As Integer
    Public Property Height() As Integer
        Get
            Return _Height
        End Get
        Set(ByVal value As Integer)
            _Height = value
        End Set
    End Property

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

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

Class BoxSameDimensions : Inherits EqualityComparer(Of Box)
    Public Overloads Overrides Function Equals(ByVal b1 As Box, _
                                      ByVal b2 As Box) As Boolean
        If b1 Is Nothing AndAlso b2 Is Nothing Then
           Return True
        Else If b1 Is Nothing OrElse b2 Is Nothing Then
           Return False
        End If

        Return (b1.Height = b2.Height AndAlso b1.Length = b2.Length _
                                      AndAlso b1.Width = b2.Width)
    End Function

    Public Overloads Overrides Function GetHashCode(ByVal bx As Box) As Integer
        Dim hCode As Integer = bx.Height Xor bx.Length Xor bx.Width
        Return hCode.GetHashCode()
    End Function
End Class

Class BoxSameVolume : Inherits EqualityComparer(Of Box)
    Public Overloads Overrides Function Equals(ByVal b1 As Box, _
                                          ByVal b2 As Box) As Boolean
        If b1 Is Nothing AndAlso b2 Is Nothing Then
           Return True
        Else If b1 Is Nothing OrElse b2 Is Nothing Then
           Return False
        End If

        Return (b1.Height * b1.Width * b1.Length = _
                b2.Height * b2.Width * b2.Length)
    End Function

    Public Overloads Overrides Function GetHashCode(ByVal bx As Box) As Integer
        Dim hCode As Integer = bx.Height * bx.Length * bx.Width
        Return hCode.GetHashCode()
    End Function
End Class
' This example produces an output similar to the following:
' * 
'    Boxes equality by dimensions:
'    Added red, Count = 1, HashCode = 46104728
'    Added green, Count = 2, HashCode = 12289376
'    A box equal to blue is already in the collection.
'    Added yellow, Count = 3, HashCode = 43495525
'
'    Boxes equality by volume:
'    Added pink, Count = 1, HashCode = 55915408
'    Added orange, Count = 2, HashCode = 33476626
'    A box equal to purple is already in the collection.
'    A box equal to brown is already in the collection.
' * 
'

설명

이 클래스에서 파생되어 제네릭 클래스와 같은 컬렉션 클래스 또는 와 같은 메서드List<T>.Sort와 함께 사용할 제네릭 인터페이스의 IEqualityComparer<T>Dictionary<TKey,TValue> 사용자 지정 구현을 제공합니다.

속성은 Default 형식 T 이 제네릭 인터페이스를 System.IEquatable<T> 구현하는지 여부를 확인하고, 이 경우 메서드의 구현을 호출하는 을 IEquatable<T>.Equals 반환 EqualityComparer<T> 합니다. 그렇지 않으면 에서 제공하는 T대로 를 EqualityComparer<T>반환합니다.

.NET 8 이상 버전에서는 메서드를 EqualityComparer<T>.Create(Func<T,T,Boolean>, Func<T,Int32>) 사용하여 이 형식의 인스턴스를 만드는 것이 좋습니다.

생성자

EqualityComparer<T>()

EqualityComparer<T> 클래스의 새 인스턴스를 초기화합니다.

속성

Default

제네릭 인수에서 지정한 형식의 기본 같음 비교자를 반환합니다.

메서드

Create(Func<T,T,Boolean>, Func<T,Int32>)

EqualityComparer<T> 지정된 대리자를 비교자의 및 GetHashCode(T) 메서드 구현으로 사용하여 을 Equals(T, T) 만듭니다.

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
Equals(T, T)

파생 클래스에서 재정의된 경우 T 형식의 두 개체가 같은지 여부를 확인합니다.

GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetHashCode(T)

파생 클래스에서 재정의된 경우 해시 테이블 같은 해시 알고리즘과 데이터 구조의 지정한 개체에 대한 해시 함수의 역할을 합니다.

GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ToString()

현재 개체를 나타내는 문자열을 반환합니다.

(다음에서 상속됨 Object)

명시적 인터페이스 구현

IEqualityComparer.Equals(Object, Object)

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

IEqualityComparer.GetHashCode(Object)

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

적용 대상

추가 정보