Editar

Partilhar via


IEquatable<T>.Equals(T) Method

Definition

Indicates whether the current object is equal to another object of the same type.

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

Parameters

other
T

An object to compare with this object.

Returns

true if the current object is equal to the other parameter; otherwise, false.

Examples

The following example shows the partial implementation of a Person class that implements IEquatable<T> and has two properties, LastName and NationalId. NationalId is considered to be a unique identifier, therefore the Equals method returns True if the NationalId property of two Person objects is identical; otherwise, it returns False.
(Note that the F# example does not handle null values for Person instances.)

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

When a Person is stored in a List<T>, Contains uses its Equals implementation to search for a match.

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

Remarks

The implementation of the Equals method is intended to perform a test for equality with another object of type T, the same type as the current object. The Equals(T) method is called in the following circumstances:

In other words, to handle the possibility that objects of a class will be stored in an array or a generic collection object, it is a good idea to implement IEquatable<T> so that the object can be easily identified and manipulated.

When implementing the Equals method, define equality appropriately for the type specified by the generic type argument. For example, if the type argument is Int32, define equality appropriately for the comparison of two 32-bit signed integers.

Notes to Implementers

If you implement Equals(T), you should also override the base class implementations of Equals(Object) and GetHashCode() so that their behavior is consistent with that of the Equals(T) method. If you do override Equals(Object), your overridden implementation is also called in calls to the static Equals(System.Object, System.Object) method on your class. In addition, you should overload the op_Equality and op_Inequality operators. This ensures that all tests for equality return consistent results, which the example illustrates.

Applies to