EqualityComparer<T>.Default Property


제네릭 인수에서 지정한 형식의 기본 같음 비교자를 반환합니다.Returns a default equality comparer for the type specified by the generic argument.

 static property System::Collections::Generic::EqualityComparer<T> ^ Default { System::Collections::Generic::EqualityComparer<T> ^ get(); };
public static System.Collections.Generic.EqualityComparer<T> Default { get; }
member this.Default : System.Collections.Generic.EqualityComparer<'T>
Public Shared ReadOnly Property Default As EqualityComparer(Of T)

Property Value


T 형식에 대한 EqualityComparer<T> 클래스의 기본 인스턴스입니다.The default instance of the EqualityComparer<T> class for type T.


다음 예제에서는 Box 형식의 요소를 포함 하는 컬렉션을 만든 다음 FindFirst 메서드를 두 번 호출 하 여 다른 상자와 일치 하는 상자를 검색 합니다.The following example creates a collection that contains elements of the Box type and then searches it for a box matching another box by calling the FindFirst method, twice.

첫 번째 검색은 같음 비교자를 지정 하지 않습니다. 즉, FindFirst EqualityComparer<T>.Default를 사용 하 여 상자의 같음을 결정 합니다.The first search does not specify any equality comparer, which means FindFirst uses EqualityComparer<T>.Default to determine equality of boxes. 그러면 Box 클래스에서 IEquatable<T>.Equals 메서드의 구현이 사용 됩니다.That in turn uses the implementation of the IEquatable<T>.Equals method in the Box class. 두 상자는 차원을 동일한 경우 같은 것으로 간주 됩니다.Two boxes are considered equal if their dimensions are the same.

두 번째 검색은 볼륨별 같음을 정의 하는 같음 비교자 (BoxEqVolume)를 지정 합니다.The second search specifies an equality comparer (BoxEqVolume) that defines equality by volume. 해당 볼륨이 동일한 두 상자 간주 됩니다.Two boxes are considered equal if their volumes are the same.

using System;
using System.Collections.Generic;

static class Program
    static void Main()
        var redBox = new Box(8, 8, 4);
        var blueBox = new Box(6, 8, 4);
        var greenBox = new Box(4, 8, 8);

        var boxes = new[] { redBox, blueBox, greenBox };

        var boxToFind = new Box(4, 8, 8);

        var foundByDimension = boxes.FindFirst(boxToFind);

        Console.WriteLine($"Found box {foundByDimension} by dimension.");

        var foundByVolume = boxes.FindFirst(boxToFind, new BoxEqVolume());

        Console.WriteLine($"Found box {foundByVolume} by volume.");

public static class CollectionExtensions
    public static T FindFirst<T>(
        this IEnumerable<T> collection, T itemToFind, IEqualityComparer<T> comparer = null)
        comparer = comparer ?? EqualityComparer<T>.Default;

        foreach (var item in collection)
            if (comparer.Equals(item, itemToFind))
                return item;

        throw new InvalidOperationException("No matching item found.");

public class BoxEqVolume : EqualityComparer<Box>
    public override bool Equals(Box b1, Box b2)
        if (object.ReferenceEquals(b1, b2))
            return true;

        if (b1 is null || b2 is null)
            return false;

        return b1.Volume == b2.Volume;

    public override int GetHashCode(Box box) => box.Volume.GetHashCode();

public class Box : IEquatable<Box>
    public Box(int height, int length, int width)
        this.Height = height;
        this.Length = length;
        this.Width = width;

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

    public int Volume => Height * Length * Width;

    public bool Equals(Box other)
        if (other is null)
            return false;

        return this.Height == other.Height && this.Length == other.Length
            && this.Width == other.Width;

    public override bool Equals(object obj) => Equals(obj as Box);
    public override int GetHashCode() => (Height, Length, Width).GetHashCode();

    public override string ToString() => $"{Height} x {Length} x {Width}";

/* This example produces the following output:
    Found box 4 x 8 x 8 by dimension.
    Found box 8 x 8 x 4 by volume.
Imports System.Collections.Generic
Imports System.Runtime.CompilerServices

Public Class Example
    Public Shared Sub Main()
        Dim redBox As New Box(8, 8, 4)
        Dim blueBox As New Box(6, 8, 4)
        Dim greenBox As New Box(4, 8, 8)

        Dim boxes As Box() = { redBox, blueBox, greenBox }

        Dim boxToFind As New Box(4, 8, 8)

        Dim foundByDimension = boxes.FindFirst(boxToFind)

        Console.WriteLine($"Found box {foundByDimension} by dimension.")

        Dim foundByVolume = boxes.FindFirst(boxToFind, New BoxEqVolume())

        Console.WriteLine($"Found box {foundByVolume} by volume.")
    End Sub

    Private Shared Sub PrintBoxCollection(boxes As Dictionary(Of Box, String))
        For Each kvp As KeyValuePair(Of Box, String) In boxes
            Console.WriteLine($"{kvp.Key.Height} x {kvp.Key.Length} x {kvp.Key.Width} - {kvp.Value}")
    End Sub
End Class

Public Module CollectionExtensions
    Public Function FindFirst(Of T)(
        collection As IEnumerable(Of T), itemToFind As T, Optional comparer As IEqualityComparer(Of T) = Nothing)

        comparer = If(comparer, EqualityComparer(Of T).Default)

        For Each item In collection
            If comparer.Equals(item, itemToFind)
                Return item
            End IF

        Throw New InvalidOperationException("No matching item found.")
    End Function
End Module

Public Class BoxEqVolume
    Inherits EqualityComparer(Of Box)

    Public Overrides Function GetHashCode(box As Box) As Integer
        Return box.Volume.GetHashCode()
    End Function

    Public Overrides Function Equals(b1 As Box, b2 As Box) As Boolean
        If b1 Is b2 Then
            Return True
        End If

        If b1 Is Nothing OrElse b2 Is Nothing Then
            Return False
        End If

        Return b1.Volume = b2.Volume
    End Function
End Class

Public Class Box
    Implements IEquatable(Of Box)

    Public Sub New(height As Integer, length As Integer, width As Integer)
        Me.Height = height
        Me.Length = length
        Me.Width = width
    End Sub

    Public ReadOnly Property Height() As Integer
    Public ReadOnly Property Length() As Integer
    Public ReadOnly Property Width() As Integer

    Public ReadOnly Property Volume() As Integer
            Return Height * Length * Width
        End Get
    End Property

    Public Overloads Function Equals(other As Box) As Boolean Implements IEquatable(Of Box).Equals
        If other Is Nothing Then
            Return False
        End If

        Return Me.Height = other.Height AndAlso Me.Length = other.Length AndAlso
            Me.Width = other.Width
    End Function

    Public Overrides Function Equals(other As Object) As Boolean
        Return Equals(TryCast(other, Box))
    End Function

    Public Overrides Function GetHashCode() As Integer
        Return (Height, Length, Width).GetHashCode()
    End Function

    Public Overrides Function ToString() As String
        Return $"{Height} x {Length} x {Width}"
    End Function
End Class
' This example produces the following output:
' Found box 4 x 8 x 8 by dimension.
' Found box 8 x 8 x 4 by volume.


Default 속성은 형식 T에서 System.IEquatable<T> 인터페이스를 구현 하는지 여부를 확인 하 고, 해당 구현을 사용 하는 EqualityComparer<T>을 반환 합니다.The Default property checks whether type T implements the System.IEquatable<T> interface and, if so, returns an EqualityComparer<T> that uses that implementation. 그렇지 않으면 T에서 제공 하는 Object.GetHashCodeObject.Equals의 재정의를 사용 하는 EqualityComparer<T>를 반환 합니다.Otherwise, it returns an EqualityComparer<T> that uses the overrides of Object.Equals and Object.GetHashCode provided by T.

Applies to

See also