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);

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 pokazano częściową implementację Person klasy, która implementuje IEquatable<T> i ma dwie właściwości: LastName i SSN. Metoda Equals zwraca True wartość , jeśli SSN właściwość dwóch Person obiektów jest identyczna; w przeciwnym razie zwraca wartość False.

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));
   }
}

Person obiekty mogą być następnie przechowywane w List<T> obiekcie i można je zidentyfikować za pomocą Contains metody , jak pokazano w poniższym przykładzie.

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.

Uwagi

Implementacja Equals metody jest przeznaczona do wykonania testu 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, należy odpowiednio zdefiniować równość dla porównania dwóch 32-bitowych liczb całkowitych ze znakiem.

Uwagi dotyczące implementowania

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

Dotyczy

Produkt Wersje
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0