IEquatable<T>.Equals(T) 메서드

정의

현재 개체가 동일한 형식의 다른 개체와 같은지 여부를 나타냅니다.Indicates whether the current object is equal to another object of the same type.

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

이 개체와 비교할 개체입니다.An object to compare with this object.

반환

현재 개체가 other 매개 변수와 같으면 true이고, 그렇지 않으면 false입니다.true if the current object is equal to the other parameter; otherwise, false.

예제

다음 예제에서는 부분 구현을 보여 줍니다.는 Person 구현 하는 클래스 IEquatable<T> 있고 두 개의 속성인 LastNameSSN합니다.The following example shows the partial implementation of a Person class that implements IEquatable<T> and has two properties, LastName and SSN. Equals 메서드가 반환 True 경우는 SSN 의 두 속성 Person 개체 동일;를 반환 합니다 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 개체에 저장 될 수는 List<T> 개체를 식별할 수 있습니다는 Contains 메서드를 다음 예제와 같이 합니다.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.

설명

구현의 합니다 Equals 메서드가 형식의 다른 개체와 같은지 테스트를 수행 하기 위한 T를 현재 개체와 동일한 형식입니다.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. Equals(T) 메서드는 다음과 같은 상황에서 호출 됩니다.The Equals(T) method is called in the following circumstances:

즉, 배열 또는 제네릭 컬렉션 개체에서 클래스의 개체를 저장할 가능성을 처리 하는 것이 구현 하는 것이 좋습니다 IEquatable<T> 개체를 쉽게 식별 하 고 조작할 수 있도록 합니다.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.

구현 하는 경우는 Equals 메서드, 제네릭 형식 인수에 의해 지정 된 형식에 맞게 같음을 정의 합니다.When implementing the Equals method, define equality appropriately for the type specified by the generic type argument. 예를 들어 형식 인수가 Int32, 두 개의 32 비트 부호 있는 정수 비교에 적합 한 같음을 정의 합니다.For example, if the type argument is Int32, define equality appropriately for the comparison of two 32-bit signed integers.

구현자 참고

구현 하는 경우 Equals(T)의 기본 클래스 구현을 재정의 해야 Equals(Object) 하 고 GetHashCode() 동작의 해당 값과 일치 되도록는 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. 재정의 하는 경우 Equals(Object), 정적 호출에서 재정의 된 구현 라고 Equals(System.Object, System.Object) 클래스에서 메서드.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. 또한를 오버 로드 해야 합니다 op_Equalityop_Inequality 연산자입니다.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.

적용 대상