Cet article a fait l’objet d’une traduction automatique. Pour afficher l’article en anglais, activez la case d’option Anglais. Vous pouvez également afficher le texte anglais dans une fenêtre contextuelle en faisant glisser le pointeur de la souris sur le texte traduit.
Traduction
Anglais

IEquatable<T>.Equals méthode (T)

 

Date de publication : novembre 2016

Indique si l'objet actuel est égal à un autre objet du même type.

Espace de noms:   System
Assembly:  mscorlib (dans mscorlib.dll)

bool Equals(
	T other
)

Paramètres

other
Type: T

Objet à comparer à cet objet.

Valeur de retour

Type: System.Boolean

true si l'objet actuel est égal au paramètre other ; sinon, false.

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

  • When the Equals method is called and the other parameter represents a strongly-typed object of type T. (If other is of type T:System.Object, the base M:System.Object.Equals(System.Object) method is called. Of the two methods, M:System.IEquatable`1.Equals(`0) offers slightly better performance.)

  • When the search methods of a number of generic collection objects are called. Some of these types and their methods include the following:

    • Some of the generic overloads of the M:System.Array.BinarySearch(System.Array,System.Object) method.

    • The search methods of the T:System.Collections.Generic.List`1 class, including M:System.Collections.Generic.List`1.Contains(`0), M:System.Collections.Generic.List`1.IndexOf(`0), M:System.Collections.Generic.List`1.LastIndexOf(`0), and M:System.Collections.Generic.List`1.Remove(`0).

    • The search methods of the T:System.Collections.Generic.Dictionary`2 class, including M:System.Collections.Generic.Dictionary`2.ContainsKey(`0) and M:System.Collections.Generic.IDictionary`2.Remove(`0).

    • The search methods of the generic T:System.Collections.Generic.LinkedList`1 class, including M:System.Collections.Generic.LinkedList`1.Contains(`0) and M:System.Collections.Generic.LinkedList`1.Remove(System.Collections.Generic.LinkedListNode{`0}).

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 T:System.IEquatable`1 so that the object can be easily identified and manipulated.

When implementing the M:System.IEquatable`1.Equals(`0) method, define equality appropriately for the type specified by the generic type argument. For example, if the type argument is T:System.Int32, define equality appropriately for the comparison of two 32-bit signed integers.

Remarques à l’attention des implémenteurs :

If you implement M:System.IEquatable`1.Equals(`0), you should also override the base class implementations of M:System.Object.Equals(System.Object) and M:System.Object.GetHashCode so that their behavior is consistent with that of the M:System.IEquatable`1.Equals(`0) method. If you do override M:System.Object.Equals(System.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.

The following example shows the partial implementation of a Person class that implements T:System.IEquatable`1 and has two properties, LastName and SSN. The M:System.IEquatable`1.Equals(`0) method returns True if the SSN property of two Person objects is identical; otherwise, it returns 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 = String.Format("{0}-(1}-{2}", 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.");

      uniqueSsn = ssn;
      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 objects can then be stored in a List<T> object and can be identified by the Contains method, as the following example shows.

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.

Plateforme Windows universelle
Disponible depuis 8
.NET Framework
Disponible depuis 2.0
Bibliothèque de classes portable
Pris en charge dans : plateformes .NET portables
Silverlight
Disponible depuis 2.0
Silverlight pour Windows Phone
Disponible depuis 7.0
Windows Phone
Disponible depuis 8.1
Retour au début
Afficher: