IEqualityComparer<T> Interface

Definição

Define métodos para dar suporte à comparação de objetos para igualdade.

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)

Parâmetros de tipo

T

O tipo de objetos a serem comparados.

Este parâmetro de tipo é contravariante. Isso significa que é possível usar o tipo especificado ou qualquer tipo menos derivado. Para obter mais informações sobre covariância e contravariância, consulte Covariância e contravariância em genéricos.
Derivado

Exemplos

O exemplo a seguir adiciona objetos personalizados Box a uma coleção de dicionários. Os Box objetos serão considerados iguais se suas dimensões forem as mesmas.

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.

Comentários

Essa interface permite a implementação de comparação de igualdade personalizada para coleções. Ou seja, você pode criar sua própria definição de igualdade para o tipo Te especificar que essa definição seja usada com um tipo de coleção que aceite a IEqualityComparer<T> interface genérica. No .NET Framework, os construtores do Dictionary<TKey,TValue> tipo de coleção genérica aceitam essa interface.

Uma implementação padrão dessa interface é fornecida pela Default propriedade da EqualityComparer<T> classe genérica. A StringComparer classe implementa IEqualityComparer<T> do tipo String.

Essa interface dá suporte apenas a comparações de igualdade. A personalização de comparações para classificação e ordenação é fornecida pela IComparer<T> interface genérica.

É recomendável derivar da EqualityComparer<T> classe em vez de implementar a IEqualityComparer<T> interface , pois a EqualityComparer<T> classe testa a igualdade usando o IEquatable<T>.Equals método em vez do Object.Equals método . Isso é consistente com os Containsmétodos , IndexOf, LastIndexOfe Remove da Dictionary<TKey,TValue> classe e de outras coleções genéricas.

Métodos

Equals(T, T)

Determina se os objetos especificados são iguais.

GetHashCode(T)

Retorna um código hash para o objeto especificado.

Aplica-se a

Confira também