共用方式為


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

要與此物件進行比較的物件。

傳回

Boolean

若目前的物件等於 true 參數,則為 other,否則即為 false

範例

下列範例顯示實作 和 具有兩個 Person 屬性之類別 IEquatable<T> 的部分實作, LastNameSSN 。 如果 SSN 兩個 物件的 屬性相同,則 Equals 方法會傳回 True ,否則會傳 False Person 回 。

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class Person : IEquatable<Person>
{
   private string uniqueSsn;
   private string lName;

   public Person(string lastName, string ssn)
   {
      if (Regex.IsMatch(ssn, @"\d{9}"))
        uniqueSsn = $"{ssn.Substring(0, 3)}-{ssn.Substring(3, 2)}-{ssn.Substring(5, 4)}";
      else if (Regex.IsMatch(ssn, @"\d{3}-\d{2}-\d{4}"))
         uniqueSsn = ssn;
      else
         throw new FormatException("The social security number has an invalid format.");

      this.LastName = lastName;
   }

   public string SSN
   {
      get { return this.uniqueSsn; }
   }

   public string LastName
   {
      get { return this.lName; }
      set {
         if (String.IsNullOrEmpty(value))
            throw new ArgumentException("The last name cannot be null or empty.");
         else
            this.lName = value;
      }
   }

   public bool Equals(Person other)
   {
      if (other == null)
         return false;

      if (this.uniqueSsn == other.uniqueSsn)
         return true;
      else
         return false;
   }

   public override bool Equals(Object obj)
   {
      if (obj == null)
         return false;

      Person personObj = obj as Person;
      if (personObj == null)
         return false;
      else
         return Equals(personObj);
   }

   public override int GetHashCode()
   {
      return this.SSN.GetHashCode();
   }

   public static bool operator == (Person person1, Person person2)
   {
      if (((object)person1) == null || ((object)person2) == null)
         return Object.Equals(person1, person2);

      return person1.Equals(person2);
   }

   public static bool operator != (Person person1, Person person2)
   {
      if (((object)person1) == null || ((object)person2) == null)
         return ! Object.Equals(person1, person2);

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

type Person(lastName, ssn) =
    let mutable lastName = lastName
    let ssn = 
        if Regex.IsMatch(ssn, @"\d{9}") then
            $"{ssn.Substring(0, 3)}-{ssn.Substring(3, 2)}-{ssn.Substring(5, 4)}"
        elif Regex.IsMatch(ssn, @"\d{3}-\d{2}-\d{4}") then
            ssn
        else
            raise (FormatException "The social security number has an invalid format.")

    member _.SSN =
        ssn

    member _.LastName
        with get () = lastName
        and set (value) =
            if String.IsNullOrEmpty value then
                invalidArg (nameof value) "The last name cannot be null or empty."
            else
                lastName <- value

    static member op_Equality (person1: Person, person2: Person) =
        if box person1 |> isNull || box person2 |> isNull then
            Object.Equals(person1, person2)
        else
            person1.Equals person2

    static member op_Inequality (person1: Person, person2: Person) =
        if box person1 |> isNull || box person2 |> isNull then
            Object.Equals(person1, person2) |> not
        else
            person1.Equals person2 |> not

    override _.GetHashCode() =
        ssn.GetHashCode()

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

    interface IEquatable<Person> with
        member this.Equals(other: Person) =
            match box other with 
            | null -> false
            | _ ->
                this.SSN = other.SSN
Imports System.Collections.Generic
Imports System.Text.RegularExpressions

Public Class Person : Implements IEquatable(Of Person)
   Private uniqueSsn As String
   Private lName As String
   
   Public Sub New(lastName As String, ssn As String)
      If Regex.IsMatch(ssn, "\d{9}") Then
         uniqueSsn = $"{ssn.Substring(0, 3)}-{ssn.Substring(3, 2)}-{ssn.Substring(5, 4)}"
      ElseIf Regex.IsMatch(ssn, "\d{3}-\d{2}-\d{4}") Then
         uniqueSsn = ssn
      Else 
         Throw New FormatException("The social security number has an invalid format.")
      End If
      Me.LastName = lastName
   End Sub
   
   Public ReadOnly Property SSN As String
      Get
         Return Me.uniqueSsn
      End Get      
   End Property
   
   Public Property LastName As String
      Get
         Return Me.lName
      End Get
      Set
         If String.IsNullOrEmpty(value) Then
            Throw New ArgumentException("The last name cannot be null or empty.")
         Else
            lname = value
         End If   
      End Set
   End Property
   
   Public Overloads Function Equals(other As Person) As Boolean _
                   Implements IEquatable(Of Person).Equals
      If other Is Nothing Then Return False
      
      If Me.uniqueSsn = other.uniqueSsn Then
         Return True
      Else
         Return False
      End If
   End Function

   Public Overrides Function Equals(obj As Object) As Boolean
      If obj Is Nothing Then Return False
      
      Dim personObj As Person = TryCast(obj, Person)
      If personObj Is Nothing Then
         Return False
      Else   
         Return Equals(personObj)   
      End If
   End Function   
   
   Public Overrides Function GetHashCode() As Integer
      Return Me.SSN.GetHashCode()
   End Function
   
   Public Shared Operator = (person1 As Person, person2 As Person) As Boolean
      If person1 Is Nothing OrElse person2 Is Nothing Then
         Return Object.Equals(person1, person2)
      End If
         
      Return person1.Equals(person2)
   End Operator
   
   Public Shared Operator <> (person1 As Person, person2 As Person) As Boolean
      If person1 Is Nothing OrElse person2 Is Nothing Then
         Return Not Object.Equals(person1, person2) 
      End If
      
      Return Not person1.Equals(person2)
   End Operator
End Class

Person 然後,物件可以儲存在 物件中 List<T> ,而且可由 方法識別 Contains ,如下列範例所示。

public class TestIEquatable
{
   public static void Main()
   {
      // Create a Person object for each job applicant.
      Person applicant1 = new Person("Jones", "099-29-4999");
      Person applicant2 = new Person("Jones", "199-29-3999");
      Person applicant3 = new Person("Jones", "299-49-6999");

      // Add applicants to a List object.
      List<Person> applicants = new List<Person>();
      applicants.Add(applicant1);
      applicants.Add(applicant2);
      applicants.Add(applicant3);

       // Create a Person object for the final candidate.
       Person candidate = new Person("Jones", "199-29-3999");
       if (applicants.Contains(candidate))
          Console.WriteLine("Found {0} (SSN {1}).",
                             candidate.LastName, candidate.SSN);
      else
         Console.WriteLine("Applicant {0} not found.", candidate.SSN);

      // Call the shared inherited Equals(Object, Object) method.
      // It will in turn call the IEquatable(Of T).Equals implementation.
      Console.WriteLine("{0}({1}) already on file: {2}.",
                        applicant2.LastName,
                        applicant2.SSN,
                        Person.Equals(applicant2, candidate));
   }
}
// The example displays the following output:
//       Found Jones (SSN 199-29-3999).
//       Jones(199-29-3999) already on file: True.
// Create a Person object for each job applicant.
let applicant1 = Person("Jones", "099-29-4999")
let applicant2 = Person("Jones", "199-29-3999")
let applicant3 = Person("Jones", "299-49-6999")

// Add applicants to a List object.
let applicants = ResizeArray()
applicants.Add applicant1
applicants.Add applicant2
applicants.Add applicant3

// Create a Person object for the final candidate.
let candidate = Person("Jones", "199-29-3999")
if applicants.Contains candidate then
    printfn $"Found {candidate.LastName} (SSN {candidate.SSN})."
else
    printfn $"Applicant {candidate.SSN} not found."

// Call the shared inherited Equals(Object, Object) method.
// It will in turn call the IEquatable<T>.Equals implementation.
printfn $"{applicant2.LastName}({applicant2.SSN}) already on file: {Person.Equals(applicant2, candidate)}."

// The example displays the following output:
//       Found Jones (SSN 199-29-3999).
//       Jones(199-29-3999) already on file: True.
Module TestIEquatable
   Public Sub Main()
      ' Create a Person object for each job applicant.
      Dim applicant1 As New Person("Jones", "099-29-4999")
      Dim applicant2 As New Person("Jones", "199-29-3999")
      Dim applicant3 As New Person("Jones", "299-49-6999")

      ' Add applicants to a List object.
      Dim applicants As New List(Of Person)
      applicants.Add(applicant1)
      applicants.Add(applicant2)
      applicants.Add(applicant3)
      
      ' Create a Person object for the final candidate.
      Dim candidate As New Person("Jones", "199-29-3999")
      
      If applicants.Contains(candidate) Then
         Console.WriteLine("Found {0} (SSN {1}).", _
                            candidate.LastName, candidate.SSN)
      Else
         Console.WriteLine("Applicant {0} not found.", candidate.SSN)
      End If         

      ' Call the shared inherited Equals(Object, Object) method.
      ' It will in turn call the IEquatable(Of T).Equals implementation.
      Console.WriteLine("{0}({1}) already on file: {2}.", _ 
                        applicant2.LastName, _
                        applicant2.SSN, _
                        Person.Equals(applicant2, candidate)) 
   End Sub
End Module
' The example displays the following output:
'       Found Jones (SSN 199-29-3999).
'       Jones(199-29-3999) already on file: True.

備註

方法的實作 Equals 是針對與類型 T 為 的另一個物件執行相等的測試,其類型與目前物件相同。 在 Equals(T) 下列情況下會呼叫 方法:

換句話說,若要處理類別的物件儲存在陣列或泛型集合物件的可能性,最好 IEquatable<T> 實作 ,以便輕鬆識別及操作物件。

實作 Equals 方法時,請適當地為泛型型別引數所指定的型別定義相等。 例如,如果 type 引數為 Int32 ,請適當地定義相等,以比較兩個 32 位帶正負號的整數。

給實施者的注意事項

如果您實作 Equals(T) ,則也應該覆寫 的基類實 Equals(Object) 作, GetHashCode() 使其行為與 Equals(T) 方法的行為一致。 如果您覆寫 Equals(Object) ,則會在呼叫 類別上的靜態 Equals(System.Object, System.Object) 方法時呼叫覆寫的實作。 此外,您應該多載 op_Equalityop_Inequality 運算子。 這可確保所有相等測試都會傳回一致的結果,此範例會加以說明。

適用於