IEquatable<T>.Equals(T) Methode
Definition
Gibt an, ob das aktuelle Objekt gleich einem anderen Objekt des gleichen Typs ist.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
Parameter
- other
- T
Ein Objekt, das mit diesem Objekt verglichen werden soll.An object to compare with this object.
Gibt zurück
true
, wenn das aktuelle Objekt gleich dem other
-Parameter ist, andernfalls false
.true
if the current object is equal to the other
parameter; otherwise, false
.
Beispiele
Das folgende Beispiel zeigt die partielle Implementierung einer Person
Klasse, die implementiert IEquatable<T> und über zwei Eigenschaften verfügt: LastName
und SSN
.The following example shows the partial implementation of a Person
class that implements IEquatable<T> and has two properties, LastName
and SSN
. Die- Equals Methode gibt zurück True
, wenn die- SSN
Eigenschaft von zwei- Person
Objekten identisch ist, andernfalls wird zurückgegeben False
.The Equals 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 = $"{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));
}
}
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
-Objekte können dann in einem List<T> -Objekt gespeichert werden und können durch die-Methode identifiziert werden Contains
, wie im folgenden Beispiel gezeigt.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.
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.
Hinweise
Die Implementierung der- Equals Methode soll einen Test auf Gleichheit mit einem anderen Objekt vom Typ ausführen T
, und zwar mit demselben Typ wie das aktuelle Objekt.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. Die- Equals(T) Methode wird in den folgenden Situationen aufgerufen:The Equals(T) method is called in the following circumstances:
Wenn die
Equals
-Methode aufgerufen wird und das-other
Argument ein stark typisiertes Objekt vom Typ istT
.When theEquals
method is called and theother
argument is a strongly-typed object of typeT
. (Wennother
nicht vom Typ istT
, wird die Basis Object.Equals(Object) Methode aufgerufen.(Ifother
is not of typeT
, the base Object.Equals(Object) method is called. Von den beiden Methoden IEquatable<T>.Equals bietet eine etwas bessere Leistung.)Of the two methods, IEquatable<T>.Equals offers slightly better performance.)Wenn die Suchmethoden einer Reihe generischer Auflistungs Objekte aufgerufen werden.When the search methods of a number of generic collection objects are called. Einige dieser Typen und ihre Methoden umfassen Folgendes:Some of these types and their methods include the following:
Einige der generischen über Ladungen der- BinarySearch Methode.Some of the generic overloads of the BinarySearch method.
Die Suchmethoden der- List<T> Klasse, einschließlich List<T>.Contains(T) , List<T>.IndexOf , List<T>.LastIndexOf und List<T>.Remove .The search methods of the List<T> class, including List<T>.Contains(T), List<T>.IndexOf, List<T>.LastIndexOf, and List<T>.Remove.
Die Suchmethoden der Dictionary<TKey,TValue> -Klasse, einschließlich ContainsKey und Remove .The search methods of the Dictionary<TKey,TValue> class, including ContainsKey and Remove.
Die Suchmethoden der generischen LinkedList<T> Klasse, einschließlich LinkedList<T>.Contains und Remove .The search methods of the generic LinkedList<T> class, including LinkedList<T>.Contains and Remove.
Anders ausgedrückt: um die Möglichkeit zu behandeln, dass Objekte einer Klasse in einem Array oder einem generischen Auflistungs Objekt gespeichert werden, empfiehlt es sich, zu implementieren, IEquatable<T> damit das Objekt leicht identifiziert und manipuliert werden kann.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.
Definieren Sie bei der Implementierung der- Equals Methode Gleichheit entsprechend für den Typ, der vom generischen Typargument angegeben wird.When implementing the Equals method, define equality appropriately for the type specified by the generic type argument. Wenn das Typargument z Int32 . b. lautet, definieren Sie Gleichheit entsprechend für den Vergleich von 2 32-Bit-Ganzzahlen mit Vorzeichen.For example, if the type argument is Int32, define equality appropriately for the comparison of two 32-bit signed integers.
Hinweise für Ausführende
Wenn Sie implementieren Equals(T) , sollten Sie auch die Basisklassen Implementierungen von und überschreiben, Equals(Object) GetHashCode() damit ihr Verhalten mit dem der-Methode konsistent ist Equals(T) .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. Wenn Sie außer Kraft setzen Equals(Object) , wird die überschriebene Implementierung auch in Aufrufen der statischen- Equals(System.Object, System.Object)
Methode für die-Klasse aufgerufen.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. Außerdem sollten Sie die op_Equality
Operatoren und überladen op_Inequality
.In addition, you should overload the op_Equality
and op_Inequality
operators. Dadurch wird sichergestellt, dass alle Gleichheits Überprüfungen konsistente Ergebnisse zurückgeben, die im Beispiel veranschaulicht werden.This ensures that all tests for equality return consistent results, which the example illustrates.