EqualityComparer<T> EqualityComparer<T> EqualityComparer<T> EqualityComparer<T> Class

Definition

Stellt eine Basisklasse für Implementierungen der generischen IEqualityComparer<T>-Schnittstelle bereit.Provides a base class for implementations of the IEqualityComparer<T> generic interface.

generic <typename T>
public ref class EqualityComparer abstract : 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
    interface IEqualityComparer<'T>
Public MustInherit Class EqualityComparer(Of T)
Implements IEqualityComparer, IEqualityComparer(Of T)

Typparameter

T

Der Typ der zu vergleichenden Objekte.The type of objects to compare.

Vererbung
EqualityComparer<T>EqualityComparer<T>EqualityComparer<T>EqualityComparer<T>
Attribute
Implementiert

Beispiele

Im folgenden Beispiel wird eine Wörterbuch Auflistung von Objekten vom Box Typ mit einem Gleichheits Vergleich erstellt.The following example creates a dictionary collection of objects of type Box with an equality comparer. Zwei Felder werden als gleich betrachtet, wenn ihre Dimensionen identisch sind.Two boxes are considered equal if their dimensions are the same. Anschließend werden die Felder zur Auflistung hinzugefügt.It then adds the boxes to the collection.

Das Wörterbuch wird mit einem Gleichheits Vergleich neu erstellt, der Gleichheit auf eine andere Weise definiert: Zwei Felder werden als gleich betrachtet, wenn die Volumes identisch sind.The dictionary is recreated with an equality comparer that defines equality in a different way: Two boxes are considered equal if their volumes are the same.

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 the following output:
 * 
      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 the following output:
' * 
'    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.
' * 
' 

Hinweise

Leiten Sie von dieser Klasse ab, um eine benutzerdefinierte IEqualityComparer<T> Implementierung der generischen-Schnittstelle zur Verwendung mit Dictionary<TKey,TValue> Auflistungs Klassen wie der generischen List<T>.Sort-Klasse oder mit Methoden wie bereitzustellen.Derive from this class to provide a custom implementation of the IEqualityComparer<T> generic interface for use with collection classes such as the Dictionary<TKey,TValue> generic class, or with methods such as List<T>.Sort.

Die Default -Eigenschaft überprüft, T ob der System.IEquatable<T> Typ die generische-Schnittstelle implementiert, und EqualityComparer<T> IEquatable<T>.Equals gibt in diesem Fall eine zurück, die die Implementierung der-Methode aufruft.The Default property checks whether type T implements the System.IEquatable<T> generic interface and, if so, returns an EqualityComparer<T> that invokes the implementation of the IEquatable<T>.Equals method. Andernfalls wird ein EqualityComparer<T>zurückgegeben, wie von Tbereitgestellt.Otherwise, it returns an EqualityComparer<T>, as provided by T.

Es wird empfohlen, dass Sie von EqualityComparer<T> der-Klasse ableiten, IEqualityComparer<T> anstatt die-Schnitt EqualityComparer<T> Stelle zu implementieren, da die IEquatable<T>.Equals -Klasse mithilfe der Object.Equals -Methode anstelle der-Methode auf Gleichheit prüft.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. Dies entspricht Containsden Methoden, LastIndexOf IndexOf, und Remove der Dictionary<TKey,TValue> -Klasse und anderen generischen Auflistungen.This is consistent with the Contains, IndexOf, LastIndexOf, and Remove methods of the Dictionary<TKey,TValue> class and other generic collections.

Konstruktoren

EqualityComparer<T>() EqualityComparer<T>() EqualityComparer<T>() EqualityComparer<T>()

Initialisiert eine neue Instanz der EqualityComparer<T>-Klasse.Initializes a new instance of the EqualityComparer<T> class.

Eigenschaften

Default Default Default Default

Gibt für den vom generischen Argument angegebenen Typ einen Standardgleichheitsvergleich zurück.Returns a default equality comparer for the type specified by the generic argument.

Methoden

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Bestimmt, ob das angegebene Objekt mit dem aktuellen Objekt identisch ist.Determines whether the specified object is equal to the current object.

(Inherited from Object)
Equals(T, T) Equals(T, T) Equals(T, T) Equals(T, T)

Ermittelt beim Überschreiben in einer abgeleiteten Klasse, ob zwei Objekte vom Typ T gleich sind.When overridden in a derived class, determines whether two objects of type T are equal.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Fungiert als Standardhashfunktion.Serves as the default hash function.

(Inherited from Object)
GetHashCode(T) GetHashCode(T) GetHashCode(T) GetHashCode(T)

Dient beim Überschreiben in einer abgeleiteten Klasse für das angegebene Objekt als Hashfunktion für Hashalgorithmen und Datenstrukturen wie Hashtabellen.When overridden in a derived class, serves as a hash function for the specified object for hashing algorithms and data structures, such as a hash table.

GetType() GetType() GetType() GetType()

Ruft den Type der aktuellen Instanz ab.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Erstellt eine flache Kopie des aktuellen Object.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

Gibt eine Zeichenfolge zurück, die das aktuelle Objekt darstellt.Returns a string that represents the current object.

(Inherited from Object)

Explizite Schnittstellenimplementierungen

IEqualityComparer.Equals(Object, Object) IEqualityComparer.Equals(Object, Object) IEqualityComparer.Equals(Object, Object) IEqualityComparer.Equals(Object, Object)

Bestimmt, ob die angegebenen Objekte gleich sind.Determines whether the specified objects are equal.

IEqualityComparer.GetHashCode(Object) IEqualityComparer.GetHashCode(Object) IEqualityComparer.GetHashCode(Object) IEqualityComparer.GetHashCode(Object)

Gibt einen Hashcode für das angegebene Objekt zurück.Returns a hash code for the specified object.

Gilt für:

Siehe auch