IEquatable<T>.Equals(T) 메서드

정의

현재 개체가 같은 형식의 다른 개체와 같은지 여부를 나타냅니다.

public:
 bool Equals(T other);
public bool Equals(T other);
public bool Equals(T? other);
abstract member Equals : 'T -> bool
Public Function Equals (other As T) As Boolean

매개 변수

other
T

이 개체와 비교할 개체입니다.

반품

true 현재 개체가 매개 변수와 같으면 .이 other 고, false그렇지 않으면 .입니다.

예제

다음 예제에서는 두 개의 속성을 구현하고 포함하는 클래스의 Person 부분 구현을 보여 줍니다IEquatable<T>.LastNameNationalId NationalId는 고유 식별자로 간주되므로 Equals 두 개체의 속성이 같으면 True 메서드가 반환 NationalId 되고, 그렇지 않으면 반환됩니다PersonFalse. (F# 예제에서는 인스턴스에 대한 null 값을 처리 Person 하지 않습니다.)

public class Person : IEquatable<Person>
{
    public Person(string lastName, string ssn)
    {
        LastName = lastName;
        NationalId = ssn;
    }

    public string LastName { get; }

    public string NationalId { get; }

    public bool Equals(Person? other) => other is not null && other.NationalId == NationalId;

    public override bool Equals(object? obj) => Equals(obj as Person);

    public override int GetHashCode() => NationalId.GetHashCode();

    public static bool operator ==(Person person1, Person person2)
    {
        if (person1 is null)
        {
            return person2 is null;
        }

        return person1.Equals(person2);
    }

    public static bool operator !=(Person person1, Person person2)
    {
        if (person1 is null)
        {
            return person2 is not null;
        }

        return !person1.Equals(person2);
    }
}
open System

type Person(lastName: string, nationalId: string) =
    member this.LastName = lastName
    member this.NationalId = nationalId

    interface IEquatable<Person> with
        member this.Equals(other: Person) =
            other.NationalId = this.NationalId

    override this.Equals(obj: obj) =
        match obj with
        | :? Person as person -> (this :> IEquatable<Person>).Equals(person)
        | _ -> false

    override this.GetHashCode() =
        this.NationalId.GetHashCode()

    static member (==) (person1: Person, person2: Person) =
        person1.Equals(person2)

    static member (!=) (person1: Person, person2: Person) =
        not (person1.Equals(person2))
Public Class Person
    Implements IEquatable(Of Person)

    Public Sub New(lastName As String, nationalId As String)
        Me.LastName = lastName
        Me.NationalId = nationalId
    End Sub

    Public ReadOnly Property LastName As String
    Public ReadOnly Property NationalId As String

    Public Overloads Function Equals(other As Person) As Boolean Implements IEquatable(Of Person).Equals
        Return other IsNot Nothing AndAlso other.NationalId = Me.NationalId
    End Function

    Public Overrides Function Equals(obj As Object) As Boolean
        Return Equals(TryCast(obj, Person))
    End Function

    Public Overrides Function GetHashCode() As Integer
        Return NationalId.GetHashCode()
    End Function

    Public Shared Operator =(person1 As Person, person2 As Person) As Boolean
        If person1 Is Nothing Then
            Return person2 Is Nothing
        End If
        Return person1.Equals(person2)
    End Operator

    Public Shared Operator <>(person1 As Person, person2 As Person) As Boolean
        If person1 Is Nothing Then
            Return person2 IsNot Nothing
        End If
        Return Not person1.Equals(person2)
    End Operator
End Class

a가 Person 저장되면 해당 List<T> 구현을 ContainsEquals 사용하여 일치 항목을 검색합니다.

List<Person> applicants = new List<Person>()
{
    new Person("Jones", "099-29-4999"),
    new Person("Jones", "199-29-3999"),
    new Person("Jones", "299-49-6999")
};

// Create a Person object for the final candidate.
Person candidate = new Person("Jones", "199-29-3999");
bool contains = applicants.Contains(candidate);
Console.WriteLine($"{candidate.LastName} ({candidate.NationalId}) is on record: {contains}");
// The example prints the following output:
// Jones (199-29-3999) is on record: True
let applicants = 
    [ Person("Jones", "099-29-4999")
      Person("Jones", "199-29-3999")
      Person("Jones", "299-49-6999") ]

let candidate = Person("Jones", "199-29-3999")
let contains = List.contains candidate applicants
printfn "%s (%s) is on record: %b" candidate.LastName candidate.NationalId contains
// The example prints the following output:
// Jones (199-29-3999) is on record: true
Dim applicants As New List(Of Person)
applicants.Add(New Person("Jones", "099-29-4999"))
applicants.Add(New Person("Jones", "199-29-3999"))
applicants.Add(New Person("Jones", "299-49-6999"))

' Create a Person object for the final candidate.
Dim candidate As New Person("Jones", "199-29-3999")
Dim contains As Boolean = applicants.Contains(candidate)
Console.WriteLine($"{candidate.LastName} ({candidate.NationalId}) is on record: {contains}")
' The example prints the following output:
' Jones (199-29-3999) Is on record True

설명

메서드의 Equals 구현은 현재 개체와 동일한 형식의 다른 형식 T개체와 같은지 테스트하기 위한 것입니다. 메서드 Equals(T) 는 다음과 같은 상황에서 호출됩니다.

즉, 클래스의 개체가 배열 또는 제네릭 컬렉션 개체에 저장될 가능성을 처리하기 위해 개체를 쉽게 식별하고 조작할 수 있도록 구현 IEquatable<T> 하는 것이 좋습니다.

메서드를 구현할 Equals 때 제네릭 형식 인수로 지정된 형식에 대해 같음을 적절하게 정의합니다. 예를 들어 형식 인수인 Int32경우 두 개의 32비트 부가 정수 비교에 적절하게 같음을 정의합니다.

구현자 참고

구현 Equals(T)하는 경우 해당 동작이 메서드의 Equals(Object) 동작과 GetHashCode() 일치할 수 있도록 기본 클래스 구현도 재정의 Equals(T) 해야 합니다. 재정 Equals(Object)의하는 경우 재정의된 구현은 클래스의 정적 Equals(System.Object, System.Object) 메서드 호출에서도 호출됩니다. 또한 연산자와 op_Equality 연산자를 op_Inequality 오버로드해야 합니다. 이렇게 하면 같음 테스트에 대한 모든 테스트가 예제에서 보여 주는 일관된 결과를 반환합니다.

적용 대상