System.Object.Equals 메서드

이 문서에서는 이 API에 대한 참조 설명서에 대한 추가 설명서를 제공합니다.

이 문서는 메서드와 관련이 있습니다 Object.Equals(Object) .

현재 인스턴스와 obj 매개 변수 간의 비교 유형은 현재 인스턴스가 참조 형식인지 값 형식인지에 따라 달라집니다.

  • 현재 인스턴스가 참조 형식인 경우 메서드는 Equals(Object) 참조 같음을 테스트하고 메서드에 Equals(Object) 대한 호출은 메서드 호출 ReferenceEquals 과 동일합니다. 참조 같음은 비교된 개체 변수가 동일한 개체를 참조한다는 것을 의미합니다. 다음 예제에서는 이러한 비교의 결과를 보여 줍니다. 참조 형식인 클래스를 Person 정의하고 클래스 생성자를 호출하여 두 개의 새 Person 개체를 인스턴스화하고 person2값이 같은 클래스를 인스턴스 Person 화합니다person1a. 또한 다른 개체 변수person1b에 할당합니다person1a. 예제의 출력에서 보여 person1aperson1b 주듯이 동일한 개체를 참조하기 때문에 동일합니다. 그러나 person1aperson2 값이 동일하지만 같지는 않습니다.

    using System;
    
    // Define a reference type that does not override Equals.
    public class Person
    {
       private string personName;
    
       public Person(string name)
       {
          this.personName = name;
       }
    
       public override string ToString()
       {
          return this.personName;
       }
    }
    
    public class Example1
    {
       public static void Main()
       {
          Person person1a = new Person("John");
          Person person1b = person1a;
          Person person2 = new Person(person1a.ToString());
    
          Console.WriteLine("Calling Equals:");
          Console.WriteLine("person1a and person1b: {0}", person1a.Equals(person1b));
          Console.WriteLine("person1a and person2: {0}", person1a.Equals(person2));
    
          Console.WriteLine("\nCasting to an Object and calling Equals:");
          Console.WriteLine("person1a and person1b: {0}", ((object) person1a).Equals((object) person1b));
          Console.WriteLine("person1a and person2: {0}", ((object) person1a).Equals((object) person2));
       }
    }
    // The example displays the following output:
    //       person1a and person1b: True
    //       person1a and person2: False
    //
    //       Casting to an Object and calling Equals:
    //       person1a and person1b: True
    //       person1a and person2: False
    
    // Define a reference type that does not override Equals.
    type Person(name) =
        override _.ToString() =
            name
    
    let person1a = Person "John"
    let person1b = person1a
    let person2 = Person(string person1a)
    
    printfn "Calling Equals:"
    printfn $"person1a and person1b: {person1a.Equals person1b}"
    printfn $"person1a and person2: {person1a.Equals person2}"
    
    printfn "\nCasting to an Object and calling Equals:"
    printfn $"person1a and person1b: {(person1a :> obj).Equals(person1b :> obj)}"
    printfn $"person1a and person2: {(person1a :> obj).Equals(person2 :> obj)}"
    // The example displays the following output:
    //       person1a and person1b: True
    //       person1a and person2: False
    //
    //       Casting to an Object and calling Equals:
    //       person1a and person1b: True
    //       person1a and person2: False
    
    ' Define a reference type that does not override Equals.
    Public Class Person1
        Private personName As String
    
        Public Sub New(name As String)
            Me.personName = name
        End Sub
    
        Public Overrides Function ToString() As String
            Return Me.personName
        End Function
    End Class
    
    Module Example0
        Public Sub Main()
            Dim person1a As New Person1("John")
            Dim person1b As Person1 = person1a
            Dim person2 As New Person1(person1a.ToString())
    
            Console.WriteLine("Calling Equals:")
            Console.WriteLine("person1a and person1b: {0}", person1a.Equals(person1b))
            Console.WriteLine("person1a and person2: {0}", person1a.Equals(person2))
            Console.WriteLine()
    
            Console.WriteLine("Casting to an Object and calling Equals:")
            Console.WriteLine("person1a and person1b: {0}", CObj(person1a).Equals(CObj(person1b)))
            Console.WriteLine("person1a and person2: {0}", CObj(person1a).Equals(CObj(person2)))
        End Sub
    End Module
    ' The example displays the following output:
    '       Calling Equals:
    '       person1a and person1b: True
    '       person1a and person2: False
    '       
    '       Casting to an Object and calling Equals:
    '       person1a and person1b: True
    '       person1a and person2: False
    
  • 현재 인스턴스가 값 형식인 경우 메서드는 Equals(Object) 값 같음을 테스트합니다. 값 같음은 다음을 의미합니다.

    • 두 개체의 형식이 같습니다. 다음 예제와 Byte 같이 값이 12인 개체는 두 개체의 런타임 형식이 다르기 때문에 값이 12인 개체와 같지 Int32 않습니다.

      byte value1 = 12;
      int value2 = 12;
      
      object object1 = value1;
      object object2 = value2;
      
      Console.WriteLine("{0} ({1}) = {2} ({3}): {4}",
                        object1, object1.GetType().Name,
                        object2, object2.GetType().Name,
                        object1.Equals(object2));
      
      // The example displays the following output:
      //        12 (Byte) = 12 (Int32): False
      
      let value1 = 12uy
      let value2 = 12
      
      let object1 = value1 :> obj
      let object2 = value2 :> obj
      
      printfn $"{object1} ({object1.GetType().Name}) = {object2} ({object2.GetType().Name}): {object1.Equals object2}"
      
      // The example displays the following output:
      //        12 (Byte) = 12 (Int32): False
      
      Module Example2
          Public Sub Main()
              Dim value1 As Byte = 12
              Dim value2 As Integer = 12
      
              Dim object1 As Object = value1
              Dim object2 As Object = value2
      
              Console.WriteLine("{0} ({1}) = {2} ({3}): {4}",
                              object1, object1.GetType().Name,
                              object2, object2.GetType().Name,
                              object1.Equals(object2))
          End Sub
      End Module
      ' The example displays the following output:
      '       12 (Byte) = 12 (Int32): False
      
    • 두 개체의 public 및 private 필드 값은 같습니다. 다음 예제에서는 값 같음을 테스트합니다. 값 형식인 Person 구조를 정의하고 클래스 생성자를 호출 Person 하여 두 개의 새 Person 개체를 인스턴스화하고 person2값이 같은 구조를 정의합니다person1. 예제의 출력에서와 같이 두 개체 변수는 서로 다른 개체 person1 를 참조하지만 person2 개인 personName 필드에 대한 값이 같기 때문에 같습니다.

      using System;
      
      // Define a value type that does not override Equals.
      public struct Person3
      {
         private string personName;
      
         public Person3(string name)
         {
            this.personName = name;
         }
      
         public override string ToString()
         {
            return this.personName;
         }
      }
      
      public struct Example3
      {
         public static void Main()
         {
            Person3 person1 = new Person3("John");
            Person3 person2 = new Person3("John");
      
            Console.WriteLine("Calling Equals:");
            Console.WriteLine(person1.Equals(person2));
      
            Console.WriteLine("\nCasting to an Object and calling Equals:");
            Console.WriteLine(((object) person1).Equals((object) person2));
         }
      }
      // The example displays the following output:
      //       Calling Equals:
      //       True
      //
      //       Casting to an Object and calling Equals:
      //       True
      
      // Define a value type that does not override Equals.
      [<Struct>]
      type Person(personName: string) =
          override _.ToString() =
              personName
      
      let person1 = Person "John"
      let person2 = Person "John"
      
      printfn "Calling Equals:"
      printfn $"{person1.Equals person2}"
      
      printfn $"\nCasting to an Object and calling Equals:"
      printfn $"{(person1 :> obj).Equals(person2 :> obj)}"
      // The example displays the following output:
      //       Calling Equals:
      //       True
      //
      //       Casting to an Object and calling Equals:
      //       True
      
      ' Define a value type that does not override Equals.
      Public Structure Person4
          Private personName As String
      
          Public Sub New(name As String)
              Me.personName = name
          End Sub
      
          Public Overrides Function ToString() As String
              Return Me.personName
          End Function
      End Structure
      
      Module Example4
          Public Sub Main()
              Dim p1 As New Person4("John")
              Dim p2 As New Person4("John")
      
              Console.WriteLine("Calling Equals:")
              Console.WriteLine(p1.Equals(p2))
              Console.WriteLine()
      
              Console.WriteLine("Casting to an Object and calling Equals:")
              Console.WriteLine(CObj(p1).Equals(p2))
          End Sub
      End Module
      ' The example displays the following output:
      '       Calling Equals:
      '       True
      '       
      '       Casting to an Object and calling Equals:
      '       True
      

클래스는 .NET Object.Equals(Object)Object 모든 형식에 대한 기본 클래스이므로 메서드는 다른 모든 형식에 대한 기본 같음 비교를 제공합니다. 그러나 형식은 값 같음을 구현하기 위해 메서드를 재정의 Equals 하는 경우가 많습니다. 자세한 내용은 호출자에 대한 참고 사항 및 상속자에 대한 참고 섹션을 참조하세요.

Windows 런타임 대한 참고 사항

Windows 런타임 클래스에서 메서드 오버로드를 호출 Equals(Object) 할 때 재정Equals(Object)의하지 않는 클래스에 대한 기본 동작을 제공합니다. 이 기능은 .NET이 Windows 런타임 대해 제공하는 지원의 일부입니다(Windows 스토어 앱 및 Windows 런타임 .NET 지원 참조). Windows 런타임 클래스는 상속Object되지 않으며 현재 메서드를 Equals(Object) 구현하지 않습니다. 그러나 C# 또는 Visual Basic 코드에서 사용할 때 메서드와 GetHashCode 메서드가 있는 것처럼 보이며 ToStringEquals(Object).NET은 이러한 메서드에 대한 기본 동작을 제공합니다.

참고 항목

C# 또는 Visual Basic으로 작성된 Windows 런타임 클래스는 메서드 오버로드를 재정의할 Equals(Object) 수 있습니다.

발신자에 대한 참고 사항

파생 클래스는 값 같음을 구현하기 위해 메서드를 재정의 Object.Equals(Object) 하는 경우가 많습니다. 또한 형식은 일반적으로 인터페이스를 구현하여 메서드에 Equals 강력한 형식의 추가 오버로드를 IEquatable<T> 제공하는 경우가 많습니다. 메서드를 Equals 호출하여 같음을 테스트하는 경우 현재 인스턴스가 재정 Object.Equals 의되는지 여부를 알고 메서드에 대한 특정 호출 Equals 이 해결되는 방법을 이해해야 합니다. 그렇지 않으면 의도한 것과 다른 같음 테스트를 수행하고 메서드가 예기치 않은 값을 반환할 수 있습니다.

다음 예제에서 이에 대해 설명합니다. 동일한 문자열을 사용하여 세 StringBuilder 개의 개체를 인스턴스화한 다음 메서드를 Equals 네 번 호출합니다. 첫 번째 메서드 호출은 3개의 반환false을 반환true하고 다시 기본.

using System;
using System.Text;

public class Example5
{
   public static void Main()
   {
      StringBuilder sb1 = new StringBuilder("building a string...");
      StringBuilder sb2 = new StringBuilder("building a string...");

      Console.WriteLine("sb1.Equals(sb2): {0}", sb1.Equals(sb2));
      Console.WriteLine("((Object) sb1).Equals(sb2): {0}",
                        ((Object) sb1).Equals(sb2));
      Console.WriteLine("Object.Equals(sb1, sb2): {0}",
                        Object.Equals(sb1, sb2));

      Object sb3 = new StringBuilder("building a string...");
      Console.WriteLine("\nsb3.Equals(sb2): {0}", sb3.Equals(sb2));
   }
}
// The example displays the following output:
//       sb1.Equals(sb2): True
//       ((Object) sb1).Equals(sb2): False
//       Object.Equals(sb1, sb2): False
//
//       sb3.Equals(sb2): False
open System
open System.Text

let sb1 = StringBuilder "building a string..."
let sb2 = StringBuilder "building a string..."

printfn $"sb1.Equals(sb2): {sb1.Equals sb2}"
printfn $"((Object) sb1).Equals(sb2): {(sb1 :> obj).Equals sb2}"
                  
printfn $"Object.Equals(sb1, sb2): {Object.Equals(sb1, sb2)}"

let sb3 = StringBuilder "building a string..."
printfn $"\nsb3.Equals(sb2): {sb3.Equals sb2}"
// The example displays the following output:
//       sb1.Equals(sb2): True
//       ((Object) sb1).Equals(sb2): False
//       Object.Equals(sb1, sb2): False
//
//       sb3.Equals(sb2): False
Imports System.Text

Module Example5
    Public Sub Main()
        Dim sb1 As New StringBuilder("building a string...")
        Dim sb2 As New StringBuilder("building a string...")

        Console.WriteLine("sb1.Equals(sb2): {0}", sb1.Equals(sb2))
        Console.WriteLine("CObj(sb1).Equals(sb2): {0}",
                        CObj(sb1).Equals(sb2))
        Console.WriteLine("Object.Equals(sb1, sb2): {0}",
                        Object.Equals(sb1, sb2))

        Console.WriteLine()
        Dim sb3 As Object = New StringBuilder("building a string...")
        Console.WriteLine("sb3.Equals(sb2): {0}", sb3.Equals(sb2))
    End Sub
End Module
' The example displays the following output:
'       sb1.Equals(sb2): True
'       CObj(sb1).Equals(sb2): False
'       Object.Equals(sb1, sb2): False
'
'       sb3.Equals(sb2): False

첫 번째 경우 값 같음을 테스트하는 강력한 형식 StringBuilder.Equals(StringBuilder) 의 메서드 오버로드가 호출됩니다. 두 StringBuilder 개체에 할당된 문자열이 같으므로 메서드는 반환합니다 true. 그러나 재정의 StringBuilder 하지 Object.Equals(Object)않습니다. 이 때문에 개체가 StringBuilder 캐스팅될 때StringBuilder, 인스턴스가 형식 Object변수에 할당되고 메서드가 두 개체 StringBuilder 에 전달될 때 Object.Equals(Object, Object) 기본 Object.Equals(Object) 메서드Object가 호출됩니다. StringBuilder 참조 형식이므로 두 StringBuilder 개체 ReferenceEquals 를 메서드에 전달하는 것과 같습니다. 세 StringBuilder 개체 모두 동일한 문자열을 포함하지만 세 개의 고유 개체를 참조합니다. 따라서 이러한 세 가지 메서드 호출은 반환됩니다 false.

메서드를 호출 ReferenceEquals 하여 참조 같음을 위해 현재 개체를 다른 개체와 비교할 수 있습니다. Visual Basic에서는 키워드(keyword)(예If Me Is otherObject Then ...: )를 사용할 is 수도 있습니다.

상속자에 대한 참고 사항

고유한 형식을 정의할 때 해당 형식은 기본 형식의 메서드에 Equals 정의된 기능을 상속합니다. 다음 표에서는 .NET의 Equals 주요 형식 범주에 대한 메서드의 기본 구현을 나열합니다.

형식 범주 같음 정의 설명
에서 직접 파생된 클래스 Object Object.Equals(Object) 참조 같음; 호출 Object.ReferenceEquals에 해당합니다.
구조체 ValueType.Equals 값 같음; 직접 바이트 바이트 비교 또는 리플렉션을 사용한 필드별 비교 중 하나.
열거형 Enum.Equals 값은 동일한 열거형 형식과 동일한 기본 값을 가져야 합니다.
대리인 MulticastDelegate.Equals 대리자는 동일한 호출 목록의 형식이 동일해야 합니다.
인터페이스 Object.Equals(Object) 참조 같음.

리플렉션에 의존하는 같음 테스트는 성능 저하를 제공하기 때문에 값 형식의 경우 항상 재정 Equals의해야 합니다. 참조 형식의 기본 구현을 재정의 Equals 하여 참조 같음 대신 값 같음을 테스트하고 값 같음의 정확한 의미를 정의할 수도 있습니다. 동일한 인스턴스가 아니더라도 두 개체의 Equals 값이 같으면 이러한 반환 true 구현입니다. 형식의 구현자는 개체의 값을 구성하는 항목을 결정하지만 일반적으로 개체의 인스턴스 변수에 저장된 데이터의 일부 또는 전부입니다. 예를 들어 개체의 값은 문자열 String.Equals(Object)String 문자를 기반으로 합니다. 메서드는 동일한 순서로 동일한 문자를 포함하는 두 문자열 인스턴스에 대해 반환 true 하도록 메서드를 재정 Object.Equals(Object) 의합니다.

다음 예제에서는 값 같음을 테스트 하는 메서드를 재정의 Object.Equals(Object) 하는 방법을 보여 있습니다. 클래스에 대한 메서드를 재정의 Equals 합니다 Person . 같음의 기본 클래스 구현을 수락한 경우 PersonPerson 개체는 단일 개체를 참조하는 경우에만 동일합니다. 그러나 이 경우 속성 값이 같 Person.Id 으면 두 Person 개체가 같습니다.

public class Person6
{
   private string idNumber;
   private string personName;

   public Person6(string name, string id)
   {
      this.personName = name;
      this.idNumber = id;
   }

   public override bool Equals(Object obj)
   {
      Person6 personObj = obj as Person6;
      if (personObj == null)
         return false;
      else
         return idNumber.Equals(personObj.idNumber);
   }

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

public class Example6
{
   public static void Main()
   {
      Person6 p1 = new Person6("John", "63412895");
      Person6 p2 = new Person6("Jack", "63412895");
      Console.WriteLine(p1.Equals(p2));
      Console.WriteLine(Object.Equals(p1, p2));
   }
}
// The example displays the following output:
//       True
//       True
open System

type Person(name, id) =
    member _.Name = name
    member _.Id = id

    override _.Equals(obj) =
        match obj with
        | :? Person as personObj ->
            id.Equals personObj.Id
        | _ -> 
            false

    override _.GetHashCode() =
        id.GetHashCode()

let p1 = Person("John", "63412895")
let p2 = Person("Jack", "63412895")
printfn $"{p1.Equals p2}"
printfn $"{Object.Equals(p1, p2)}"
// The example displays the following output:
//       True
//       True
Public Class Person
   Private idNumber As String
   Private personName As String
   
   Public Sub New(name As String, id As String)
      Me.personName = name
      Me.idNumber = id
   End Sub
   
   Public Overrides Function Equals(obj As Object) As Boolean
      Dim personObj As Person = TryCast(obj, Person) 
      If personObj Is Nothing Then
         Return False
      Else
         Return idNumber.Equals(personObj.idNumber)
      End If   
   End Function
   
   Public Overrides Function GetHashCode() As Integer
      Return Me.idNumber.GetHashCode() 
   End Function
End Class

Module Example6
    Public Sub Main()
        Dim p1 As New Person("John", "63412895")
        Dim p2 As New Person("Jack", "63412895")
        Console.WriteLine(p1.Equals(p2))
        Console.WriteLine(Object.Equals(p1, p2))
    End Sub
End Module
' The example displays the following output:
'       True
'       True

재정의 외에도 인터페이스를 Equals구현하여 강력한 형식의 IEquatable<T> 같음 테스트를 제공할 수 있습니다.

다음 문은 메서드의 Equals(Object) 모든 구현에 대해 true여야 합니다. 목록에서 xyz null이 아닌 개체 참조를 나타냅니다.

  • x.Equals(x)은(는) true을(를) 반환합니다.

  • x.Equals(y)y.Equals(x)와 동일한 값을 반환합니다.

  • x.Equals(y)는 둘 다인 경우 를 반환 true 합니다 yNaN.x

  • 를 반환true하면 (x.Equals(y) && y.Equals(z)) .를 x.Equals(z) 반환합니다true.

  • 참조된 개체가 y 수정되지 않는 한 동일한 값을 반환하는 x.Equals(y) 연속 호출 x 입니다.

  • x.Equals(null)은(는) false을(를) 반환합니다.

구현은 예외를 Equals throw해서는 안 되며 항상 값을 반환해야 합니다. 예를 들어 이 경우 objnull메서드는 Equals .를 throw하는 ArgumentNullException대신 반환 false 해야 합니다.

재정의할 때 다음 지침을 따릅니다.Equals(Object)

  • 구현 IComparable 하는 형식은 재정 Equals(Object)의해야 합니다.

  • 재정 Equals(Object) 의하는 형식도 재정 GetHashCode의해야 합니다. 그렇지 않으면 해시 테이블이 제대로 작동하지 않을 수 있습니다.

  • 같음을 위해 강력한 형식의 IEquatable<T> 테스트를 지원하도록 인터페이스를 구현하는 것이 좋습니다. IEquatable<T>.Equals 구현 시 Equals와 일치하는 결과를 반환해야 합니다.

  • 프로그래밍 언어가 연산자 오버로드를 지원하고 지정된 형식에 대해 같음 연산자를 오버로드하는 경우 같음 연산자와 동일한 결과를 반환하도록 메서드를 재정 Equals(Object) 의해야 합니다. 이렇게 하면 사용 하는 클래스 라이브러리 코드가 Equals (같은 ArrayListHashtable) 애플리케이션 코드에서 같음 연산자를 사용 하는 방법은 일치 하는 방식으로 동작 합니다.

참조 형식에 대한 지침

참조 형식에 대한 재정의 Equals(Object) 에는 다음 지침이 적용됩니다.

  • 형식의 의미 체계가 형식이 일부 값을 나타낸다는 사실을 기반으로 하는 경우 재정 Equals 의하는 것이 좋습니다.

  • 대부분의 참조 형식은 같음 연산자를 재정의하더라도 Equals오버로드해서는 안 됩니다. 그러나 복소수 형식과 같은 값 의미 체계를 갖도록 의도된 참조 형식을 구현하는 경우 같음 연산자를 재정의해야 합니다.

  • 변경 가능한 참조 형식에서 재정 Equals 의해서는 안 됩니다. 이는 재정의를 Equals 수행하려면 이전 섹션에서 설명한 대로 메서드도 재정의 GetHashCode 해야 하기 때문입니다. 즉, 변경 가능한 참조 형식 인스턴스의 해시 코드는 수명 동안 변경될 수 있으므로 해시 테이블에서 개체가 손실될 수 있습니다.

값 형식에 대한 지침

값 형식에 대한 재정의 Equals(Object) 에는 다음 지침이 적용됩니다.

  • 값이 참조 형식인 하나 이상의 필드를 포함하는 값 형식을 정의하는 경우 재정 Equals(Object)의해야 합니다. 제공된 ValueType 구현은 Equals(Object) 필드가 모두 값 형식인 값 형식에 대해 바이트 바이트 비교를 수행하지만 리플렉션을 사용하여 필드에 참조 형식이 포함된 값 형식의 필드별 비교를 수행합니다.

  • 재정 Equals 의하고 개발 언어가 연산자 오버로드를 지원하는 경우 같음 연산자를 오버로드해야 합니다.

  • 인터페이스를 IEquatable<T> 구현해야 합니다. 강력한 형식 IEquatable<T>.Equals 의 메서드를 호출하면 인수를 boxing하지 obj 않습니다.

예제

다음 예제에서는 값 같음을 제공 하는 메서드를 재정의 Equals 하는 클래스 및 파생 Point된 클래스를 Point3D 보여 Point 줍니다. Point 값 같음을 테스트하기 위해 재정 Object.Equals(Object) 의하므로 메서드가 Object.Equals(Object) 호출되지 않습니다. 그러나 Point3D.Equals 값 같음을 제공하는 방식으로 구현 Object.Equals(Object) 되므로 호출 Point.EqualsPoint 됩니다.

using System;

class Point2
{
    protected int x, y;

    public Point2() : this(0, 0)
    { }

    public Point2(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    public override bool Equals(Object obj)
    {
        //Check for null and compare run-time types.
        if ((obj == null) || !this.GetType().Equals(obj.GetType()))
        {
            return false;
        }
        else
        {
            Point2 p = (Point2)obj;
            return (x == p.x) && (y == p.y);
        }
    }

    public override int GetHashCode()
    {
        return (x << 2) ^ y;
    }

    public override string ToString()
    {
        return String.Format("Point2({0}, {1})", x, y);
    }
}

sealed class Point3D : Point2
{
    int z;

    public Point3D(int x, int y, int z) : base(x, y)
    {
        this.z = z;
    }

    public override bool Equals(Object obj)
    {
        Point3D pt3 = obj as Point3D;
        if (pt3 == null)
            return false;
        else
            return base.Equals((Point2)obj) && z == pt3.z;
    }

    public override int GetHashCode()
    {
        return (base.GetHashCode() << 2) ^ z;
    }

    public override String ToString()
    {
        return String.Format("Point2({0}, {1}, {2})", x, y, z);
    }
}

class Example7
{
    public static void Main()
    {
        Point2 point2D = new Point2(5, 5);
        Point3D point3Da = new Point3D(5, 5, 2);
        Point3D point3Db = new Point3D(5, 5, 2);
        Point3D point3Dc = new Point3D(5, 5, -1);

        Console.WriteLine("{0} = {1}: {2}",
                          point2D, point3Da, point2D.Equals(point3Da));
        Console.WriteLine("{0} = {1}: {2}",
                          point2D, point3Db, point2D.Equals(point3Db));
        Console.WriteLine("{0} = {1}: {2}",
                          point3Da, point3Db, point3Da.Equals(point3Db));
        Console.WriteLine("{0} = {1}: {2}",
                          point3Da, point3Dc, point3Da.Equals(point3Dc));
    }
}
// The example displays the following output:
//       Point2(5, 5) = Point2(5, 5, 2): False
//       Point2(5, 5) = Point2(5, 5, 2): False
//       Point2(5, 5, 2) = Point2(5, 5, 2): True
//       Point2(5, 5, 2) = Point2(5, 5, -1): False
type Point(x, y) =
    new () = Point(0, 0)
    member _.X = x
    member _.Y = y

    override _.Equals(obj) =
        //Check for null and compare run-time types.
        match obj with
        | :? Point as p ->
            x = p.X && y = p.Y
        | _ -> 
            false

    override _.GetHashCode() =
        (x <<< 2) ^^^ y

    override _.ToString() =
        $"Point({x}, {y})"

type Point3D(x, y, z) =
    inherit Point(x, y)
    member _.Z = z

    override _.Equals(obj) =
        match obj with
        | :? Point3D as pt3 ->
            base.Equals(pt3 :> Point) && z = pt3.Z
        | _ -> 
            false

    override _.GetHashCode() =
        (base.GetHashCode() <<< 2) ^^^ z

    override _.ToString() =
        $"Point({x}, {y}, {z})"

let point2D = Point(5, 5)
let point3Da = Point3D(5, 5, 2)
let point3Db = Point3D(5, 5, 2)
let point3Dc = Point3D(5, 5, -1)

printfn $"{point2D} = {point3Da}: {point2D.Equals point3Da}"
printfn $"{point2D} = {point3Db}: {point2D.Equals point3Db}"
printfn $"{point3Da} = {point3Db}: {point3Da.Equals point3Db}"
printfn $"{point3Da} = {point3Dc}: {point3Da.Equals point3Dc}"
// The example displays the following output:
//       Point(5, 5) = Point(5, 5, 2): False
//       Point(5, 5) = Point(5, 5, 2): False
//       Point(5, 5, 2) = Point(5, 5, 2): True
//       Point(5, 5, 2) = Point(5, 5, -1): False
Class Point1
    Protected x, y As Integer

    Public Sub New()
        Me.x = 0
        Me.y = 0
    End Sub

    Public Sub New(x As Integer, y As Integer)
        Me.x = x
        Me.y = y
    End Sub

    Public Overrides Function Equals(obj As Object) As Boolean
        ' Check for null and compare run-time types.
        If obj Is Nothing OrElse Not Me.GetType().Equals(obj.GetType()) Then
            Return False
        Else
            Dim p As Point1 = DirectCast(obj, Point1)
            Return x = p.x AndAlso y = p.y
        End If
    End Function

    Public Overrides Function GetHashCode() As Integer
        Return (x << 2) Xor y
    End Function

    Public Overrides Function ToString() As String
        Return String.Format("Point1({0}, {1})", x, y)
    End Function
End Class

Class Point3D : Inherits Point1
    Private z As Integer

    Public Sub New(ByVal x As Integer, ByVal y As Integer, ByVal z As Integer)
        MyBase.New(x, y)
        Me.z = z
    End Sub

    Public Overrides Function Equals(ByVal obj As Object) As Boolean
        Dim pt3 As Point3D = TryCast(obj, Point3D)
        If pt3 Is Nothing Then
            Return False
        Else
            Return MyBase.Equals(CType(pt3, Point1)) AndAlso z = pt3.z
        End If
    End Function

    Public Overrides Function GetHashCode() As Integer
        Return (MyBase.GetHashCode() << 2) Xor z
    End Function

    Public Overrides Function ToString() As String
        Return String.Format("Point1({0}, {1}, {2})", x, y, z)
    End Function
End Class

Module Example1
    Public Sub Main()
        Dim point2D As New Point1(5, 5)
        Dim point3Da As New Point3D(5, 5, 2)
        Dim point3Db As New Point3D(5, 5, 2)
        Dim point3Dc As New Point3D(5, 5, -1)

        Console.WriteLine("{0} = {1}: {2}",
                          point2D, point3Da, point2D.Equals(point3Da))
        Console.WriteLine("{0} = {1}: {2}",
                          point2D, point3Db, point2D.Equals(point3Db))
        Console.WriteLine("{0} = {1}: {2}",
                          point3Da, point3Db, point3Da.Equals(point3Db))
        Console.WriteLine("{0} = {1}: {2}",
                          point3Da, point3Dc, point3Da.Equals(point3Dc))
    End Sub
End Module
' The example displays the following output
'       Point1(5, 5) = Point1(5, 5, 2): False
'       Point1(5, 5) = Point1(5, 5, 2): False
'       Point1(5, 5, 2) = Point1(5, 5, 2): True
'       Point1(5, 5, 2) = Point1(5, 5, -1): False

메서드는 Point.Equals 인수가 nullobj 아니고 이 개체와 동일한 형식의 인스턴스를 참조하도록 검사. 두 검사 모두 실패하면 메서드가 반환됩니다false.

메서드는 Point.Equals 메서드를 GetType 호출하여 두 개체의 런타임 형식이 동일한지 여부를 확인합니다. 메서드가 C# 또는 TryCast(obj, Point) Visual Basic에서 양식 obj is Point 의 검사 사용하는 경우 현재 인스턴스가 동일한 런타임 형식이 아니더라도 obj 파생 클래스의 Point인스턴스인 경우 obj 검사 반환 true 됩니다. 두 개체가 동일한 형식임을 확인한 후 메서드는 형식 Point 으로 캐스팅 obj 되고 두 개체의 인스턴스 필드를 비교한 결과를 반환합니다.

에서 Point3D.Equals재정의되는 Object.Equals(Object)상속된 Point.Equals 메서드는 다른 작업이 수행되기 전에 호출됩니다. Point3D 봉인된 클래스(NotInheritableVisual Basic)이므로 C# 또는 TryCast(obj, Point) Visual Basic의 양식 obj is Point 에서 검사 개체인지 확인하는 objPoint3D 데 적합합니다. 개체인 Point3D 경우 개체로 Point 캐스팅되고 기본 클래스 구현 Equals에 전달됩니다. 상속된 메서드가 반환 true 되는 Point.Equals 경우에만 메서드는 파생 클래스에 z 도입된 인스턴스 필드를 비교합니다.

다음 예제에서는 내부적으로 사각형을 Rectangle 두 개체 Point 로 구현하는 클래스를 정의합니다. 또한 클래스는 Rectangle 값 같음을 제공하도록 재정의합니다 Object.Equals(Object) .

using System;

class Rectangle
{
   private Point a, b;

   public Rectangle(int upLeftX, int upLeftY, int downRightX, int downRightY)
   {
      this.a = new Point(upLeftX, upLeftY);
      this.b = new Point(downRightX, downRightY);
   }

   public override bool Equals(Object obj)
   {
      // Perform an equality check on two rectangles (Point object pairs).
      if (obj == null || GetType() != obj.GetType())
          return false;
      Rectangle r = (Rectangle)obj;
      return a.Equals(r.a) && b.Equals(r.b);
   }

   public override int GetHashCode()
   {
      return Tuple.Create(a, b).GetHashCode();
   }

    public override String ToString()
    {
       return String.Format("Rectangle({0}, {1}, {2}, {3})",
                            a.x, a.y, b.x, b.y);
    }
}

class Point
{
  internal int x;
  internal int y;

  public Point(int X, int Y)
  {
     this.x = X;
     this.y = Y;
  }

  public override bool Equals (Object obj)
  {
     // Performs an equality check on two points (integer pairs).
     if (obj == null || GetType() != obj.GetType()) return false;
     Point p = (Point)obj;
     return (x == p.x) && (y == p.y);
  }

  public override int GetHashCode()
  {
     return Tuple.Create(x, y).GetHashCode();
  }
}

class Example
{
   public static void Main()
   {
      Rectangle r1 = new Rectangle(0, 0, 100, 200);
      Rectangle r2 = new Rectangle(0, 0, 100, 200);
      Rectangle r3 = new Rectangle(0, 0, 150, 200);

      Console.WriteLine("{0} = {1}: {2}", r1, r2, r1.Equals(r2));
      Console.WriteLine("{0} = {1}: {2}", r1, r3, r1.Equals(r3));
      Console.WriteLine("{0} = {1}: {2}", r2, r3, r2.Equals(r3));
   }
}
// The example displays the following output:
//    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 100, 200): True
//    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
//    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
type Point(x, y) =
    member _.X = x
    member _.Y = y

    override _.Equals(obj) =
        // Performs an equality check on two points (integer pairs).
        match obj with
        | :? Point as p ->
            x = p.X && y = p.Y
        | _ ->
            false
    
    override _.GetHashCode() =
        (x, y).GetHashCode()

type Rectangle(upLeftX, upLeftY, downRightX, downRightY) =
    let a = Point(upLeftX, upLeftY)
    let b = Point(downRightX, downRightY)
    
    member _.UpLeft = a
    member _.DownRight = b

    override _.Equals(obj) =
        // Perform an equality check on two rectangles (Point object pairs).
        match obj with
        | :? Rectangle as r ->
            a.Equals(r.UpLeft) && b.Equals(r.DownRight)
        | _ -> 
            false
        
    override _.GetHashCode() =
        (a, b).GetHashCode()

    override _.ToString() =
       $"Rectangle({a.X}, {a.Y}, {b.X}, {b.Y})"

let r1 = Rectangle(0, 0, 100, 200)
let r2 = Rectangle(0, 0, 100, 200)
let r3 = Rectangle(0, 0, 150, 200)

printfn $"{r1} = {r2}: {r1.Equals r2}"
printfn $"{r1} = {r3}: {r1.Equals r3}"
printfn $"{r2} = {r3}: {r2.Equals r3}"
// The example displays the following output:
//    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 100, 200): True
//    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
//    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
Class Rectangle 
    Private a, b As Point
    
    Public Sub New(ByVal upLeftX As Integer, ByVal upLeftY As Integer, _
                   ByVal downRightX As Integer, ByVal downRightY As Integer) 
        Me.a = New Point(upLeftX, upLeftY)
        Me.b = New Point(downRightX, downRightY)
    End Sub 
    
    Public Overrides Function Equals(ByVal obj As [Object]) As Boolean 
        ' Performs an equality check on two rectangles (Point object pairs).
        If obj Is Nothing OrElse Not [GetType]().Equals(obj.GetType()) Then
            Return False
        End If
        Dim r As Rectangle = CType(obj, Rectangle)
        Return a.Equals(r.a) AndAlso b.Equals(r.b)
    End Function

    Public Overrides Function GetHashCode() As Integer 
        Return Tuple.Create(a, b).GetHashCode()
    End Function 

    Public Overrides Function ToString() As String
       Return String.Format("Rectangle({0}, {1}, {2}, {3})",
                            a.x, a.y, b.x, b.y) 
    End Function
End Class 

Class Point
    Friend x As Integer
    Friend y As Integer
    
    Public Sub New(ByVal X As Integer, ByVal Y As Integer) 
        Me.x = X
        Me.y = Y
    End Sub 

    Public Overrides Function Equals(ByVal obj As [Object]) As Boolean 
        ' Performs an equality check on two points (integer pairs).
        If obj Is Nothing OrElse Not [GetType]().Equals(obj.GetType()) Then
            Return False
        Else
           Dim p As Point = CType(obj, Point)
           Return x = p.x AndAlso y = p.y
        End If
    End Function 
    
    Public Overrides Function GetHashCode() As Integer 
        Return Tuple.Create(x, y).GetHashCode()
    End Function 
End Class  

Class Example
    Public Shared Sub Main() 
        Dim r1 As New Rectangle(0, 0, 100, 200)
        Dim r2 As New Rectangle(0, 0, 100, 200)
        Dim r3 As New Rectangle(0, 0, 150, 200)
        
        Console.WriteLine("{0} = {1}: {2}", r1, r2, r1.Equals(r2))
        Console.WriteLine("{0} = {1}: {2}", r1, r3, r1.Equals(r3))
        Console.WriteLine("{0} = {1}: {2}", r2, r3, r2.Equals(r3))
    End Sub 
End Class 
' The example displays the following output:
'    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 100, 200): True
'    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False
'    Rectangle(0, 0, 100, 200) = Rectangle(0, 0, 150, 200): False

C# 및 Visual Basic 지원 연산자 오버로드와 같은 일부 언어 형식이 같음 연산자를 오버로드하는 경우 동일한 기능을 제공하려면 메서드를 재정 Equals(Object) 의해야 합니다. 이 작업은 일반적으로 다음 예제와 같이 오버로드된 같음 연산자를 기준으로 메서드를 작성 Equals(Object) 하여 수행됩니다.

using System;

public struct Complex
{
   public double re, im;

   public override bool Equals(Object obj)
   {
      return obj is Complex && this == (Complex)obj;
   }

   public override int GetHashCode()
   {
      return Tuple.Create(re, im).GetHashCode();
   }

   public static bool operator ==(Complex x, Complex y)
   {
      return x.re == y.re && x.im == y.im;
   }

   public static bool operator !=(Complex x, Complex y)
   {
      return !(x == y);
   }

    public override String ToString()
    {
       return String.Format("({0}, {1})", re, im);
    }
}

class MyClass
{
  public static void Main()
  {
    Complex cmplx1, cmplx2;

    cmplx1.re = 4.0;
    cmplx1.im = 1.0;

    cmplx2.re = 2.0;
    cmplx2.im = 1.0;

    Console.WriteLine("{0} <> {1}: {2}", cmplx1, cmplx2, cmplx1 != cmplx2);
    Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1.Equals(cmplx2));

    cmplx2.re = 4.0;

    Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1 == cmplx2);
    Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1.Equals(cmplx2));
  }
}
// The example displays the following output:
//       (4, 1) <> (2, 1): True
//       (4, 1) = (2, 1): False
//       (4, 1) = (4, 1): True
//       (4, 1) = (4, 1): True
[<Struct; CustomEquality; NoComparison>]
type Complex =
    val mutable re: double
    val mutable im: double

    override this.Equals(obj) =
        match obj with 
        | :? Complex as c when c = this -> true
        | _ -> false 

    override this.GetHashCode() =
        (this.re, this.im).GetHashCode()

    override this.ToString() =
        $"({this.re}, {this.im})"

    static member op_Equality (x: Complex, y: Complex) =
        x.re = y.re && x.im = y.im

    static member op_Inequality (x: Complex, y: Complex) =
        x = y |> not

let mutable cmplx1 = Complex()
let mutable cmplx2 = Complex()

cmplx1.re <- 4.0
cmplx1.im <- 1.0

cmplx2.re <- 2.0
cmplx2.im <- 1.0

printfn $"{cmplx1} <> {cmplx2}: {cmplx1 <> cmplx2}"
printfn $"{cmplx1} = {cmplx2}: {cmplx1.Equals cmplx2}"

cmplx2.re <- 4.0

printfn $"{cmplx1} = {cmplx2}: {cmplx1 = cmplx2}"
printfn $"{cmplx1} = {cmplx2}: {cmplx1.Equals cmplx2}"

// The example displays the following output:
//       (4, 1) <> (2, 1): True
//       (4, 1) = (2, 1): False
//       (4, 1) = (4, 1): True
//       (4, 1) = (4, 1): True
Public Structure Complex
    Public re, im As Double
    
    Public Overrides Function Equals(ByVal obj As [Object]) As Boolean 
        Return TypeOf obj Is Complex AndAlso Me = CType(obj, Complex)
    End Function 
    
    Public Overrides Function GetHashCode() As Integer 
        Return Tuple.Create(re, im).GetHashCode()
    End Function 
    
    Public Shared Operator = (x As Complex, y As Complex) As Boolean
       Return x.re = y.re AndAlso x.im = y.im
    End Operator 
    
    Public Shared Operator <> (x As Complex, y As Complex) As Boolean
       Return Not (x = y)
    End Operator 
    
    Public Overrides Function ToString() As String
       Return String.Format("({0}, {1})", re, im)
    End Function 
End Structure

Class Example8
    Public Shared Sub Main()
        Dim cmplx1, cmplx2 As Complex

        cmplx1.re = 4.0
        cmplx1.im = 1.0

        cmplx2.re = 2.0
        cmplx2.im = 1.0

        Console.WriteLine("{0} <> {1}: {2}", cmplx1, cmplx2, cmplx1 <> cmplx2)
        Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1.Equals(cmplx2))

        cmplx2.re = 4.0

        Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1 = cmplx2)
        Console.WriteLine("{0} = {1}: {2}", cmplx1, cmplx2, cmplx1.Equals(cmplx2))
    End Sub
End Class
' The example displays the following output:
'       (4, 1) <> (2, 1): True
'       (4, 1) = (2, 1): False
'       (4, 1) = (4, 1): True
'       (4, 1) = (4, 1): True

Complex 값 형식이므로 파생될 수 없습니다. 따라서 메서드에 대한 재정 Equals(Object) 의는 각 개체의 정확한 런타임 형식을 결정하기 위해 호출 GetType 할 필요가 없지만 대신 C#의 연산자 또는 TypeOf Visual Basic의 연산자를 사용하여 is 매개 변수 형식 obj 을 검사 수 있습니다.