Język

IEquatable<T>.Equals(T) Metoda

Definicja

Wskazuje, czy bieżący obiekt jest równy innemu obiektowi tego samego typu.

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

Parametry

other
T

Obiekt do porównania z tym obiektem.

Zwraca

true jeśli bieżący obiekt jest równy parametrowi other ; w przeciwnym razie false.

Przykłady

W poniższym przykładzie przedstawiono częściową implementację Person klasy, która implementuje IEquatable<T> i ma dwie właściwości oraz LastNameNationalId . NationalId jest uważany za unikatowy identyfikator, dlatego Equals metoda zwraca True , jeśli NationalId właściwość dwóch Person obiektów jest taka sama; w przeciwnym razie zwraca wartość False. (Zwróć uwagę, że przykład języka F# nie obsługuje null wartości dla Person wystąpień).

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

Gdy element Person jest przechowywany w obiekcie List<T>, Contains używa jego Equals implementacji do wyszukiwania dopasowania.

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

Uwagi

Implementacja Equals metody ma wykonać test równości z innym obiektem typu T, tego samego typu co bieżący obiekt. Metoda jest wywoływana Equals(T) w następujących okolicznościach:

Innymi słowy, aby obsłużyć możliwość, że obiekty klasy będą przechowywane w tablicy lub w obiekcie kolekcji ogólnej, dobrym pomysłem jest zaimplementowanie IEquatable<T> , aby można było łatwo zidentyfikować i manipulować obiektem.

Podczas implementowania Equals metody należy odpowiednio zdefiniować równość dla typu określonego przez argument typu ogólnego. Jeśli na przykład argument typu to Int32, zdefiniuj równość odpowiednio dla porównania dwóch 32-bitowych liczb całkowitych ze znakiem.

Notatki dotyczące implementowania

W przypadku zaimplementowania Equals(T)metody należy również zastąpić implementacje klas bazowych Equals(Object) i GetHashCode() tak, aby ich zachowanie było zgodne z Equals(T) tą metodą. Jeśli zastąpisz Equals(Object)metodę , implementacja zastąpienia jest również wywoływana w wywołaniach metody statycznej Equals(System.Object, System.Object) w klasie. Ponadto należy przeciążyć op_Equality operatory i op_Inequality . Dzięki temu wszystkie testy pod kątem równości zwracają spójne wyniki, co pokazano w przykładzie.

Dotyczy