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 のオブジェクトのディクショナリ コレクションを作成します。 寸法が同じ場合、2 つのボックスは等しいと見なされます。 次に、ボックスをコレクションに追加します。

ディクショナリは、異なる方法で等値を定義する等値比較子を使用して再作成されます。2 つのボックスは、ボリュームが同じである場合は等しいと見なされます。

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.
' * 
'

注釈

ジェネリック クラスなどのコレクション クラスまたは などのメソッドで使用するジェネリック インターフェイスの IEqualityComparer<T> カスタム実装を Dictionary<TKey,TValue> 提供するには、このクラスから派生します List<T>.Sort

プロパティは Default 、型 T がジェネリック インターフェイスを System.IEquatable<T> 実装しているかどうかを確認し、実装されている場合は、 メソッドの実装を EqualityComparer<T> 呼び出す を IEquatable<T>.Equals 返します。 それ以外の場合は、 によって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>比較子Equals(T, T)の メソッドと GetHashCode(T) メソッドの実装として、指定したデリゲートを使用して を作成します。

Equals(Object)

指定されたオブジェクトが現在のオブジェクトと等しいかどうかを判断します。

(継承元 Object)
Equals(T, T)

派生クラスでオーバーライドされた場合、T 型の 2 つのオブジェクトが等しいかどうかを確認します。

GetHashCode()

既定のハッシュ関数として機能します。

(継承元 Object)
GetHashCode(T)

派生クラスでオーバーライドされた場合、ハッシュ アルゴリズムや、ハッシュ テーブルなどのデータ構造体の指定したオブジェクトに使用するハッシュ関数として機能します。

GetType()

現在のインスタンスの Type を取得します。

(継承元 Object)
MemberwiseClone()

現在の Object の簡易コピーを作成します。

(継承元 Object)
ToString()

現在のオブジェクトを表す文字列を返します。

(継承元 Object)

明示的なインターフェイスの実装

IEqualityComparer.Equals(Object, Object)

指定したオブジェクトが等しいかどうかを判断します。

IEqualityComparer.GetHashCode(Object)

指定したオブジェクトのハッシュ コードを返します。

適用対象

こちらもご覧ください