語言

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>中時, Contains 會使用其 Equals 實作來搜尋匹配。

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。 這確保所有等式檢定結果一致,範例即為其說明。

適用於