이 문서는 이 API에 대한 참조 설명서를 보충하는 추가 설명을 제공합니다.
이 문서는 Object.Equals(Object) 메서드와 관련이 있습니다.
현재 인스턴스와 obj 매개 변수 간의 비교 유형은 현재 인스턴스가 참조 형식인지 값 형식인지에 따라 달라집니다.
현재 인스턴스가 참조 형식인 경우 메서드는 Equals(Object) 참조 같음을 테스트하고 메서드에 Equals(Object) 대한 호출은 메서드 호출 ReferenceEquals 과 동일합니다. 참조 같음은 비교된 개체 변수가 동일한 개체를 참조한다는 것을 의미합니다. 다음 예제에서는 이러한 비교의 결과를 보여 줍니다. 클래스 참조 형식인
Person을 정의하고 클래스 생성자Person를 호출하여 같은 값을 가진 두 개의 새Person개체인person1a와person2를 인스턴스화합니다.person1a을(를) 다른 개체 변수person1b에 할당합니다. 예제의 출력에서 보이는 것처럼person1a와person1b는 동일한 개체를 참조하므로 동일합니다. 그러나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: {person1a.Equals(person1b)}"); Console.WriteLine($"person1a and person2: {person1a.Equals(person2)}"); Console.WriteLine("\nCasting to an Object and calling Equals:"); Console.WriteLine($"person1a and person1b: {((object) person1a).Equals((object) person1b)}"); Console.WriteLine($"person1a and person2: {((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) 값 같음을 테스트합니다. 값 같음은 다음을 의미합니다.
두 개체의 형식이 같습니다. 다음 예제가 보여주듯이, 값이 12인 Byte 객체는 값이 12인 Int32 객체와 같지 않습니다. 이는 두 객체가 서로 다른 런타임 형식을 가지고 있기 때문입니다.
byte value1 = 12; int value2 = 12; object object1 = value1; object object2 = value2; Console.WriteLine($"{object1} ({object1.GetType().Name}) = {object2} ({object2.GetType().Name}): {object1.Equals(object2)}"); // The example displays the following output: // 12 (Byte) = 12 (Int32): Falselet 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): FalseModule 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객체person1및person2를 인스턴스화합니다. 예제의 출력에서와 같이 두 개체 변수는 서로 다른 개체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 클래스가 모든 형식의 기본 클래스이므로, Object.Equals(Object) 메서드는 다른 모든 형식에 대한 기본적인 동등성 비교를 제공합니다. 그러나 형식은 값 같음을 달성하기 위해 Equals을 재정의하는 경우가 많습니다. 자세한 내용은 호출자에 대한 참고 사항 및 상속자에 대한 참고 섹션을 참조하세요.
Windows 런타임에 대한 참고 사항
Windows 런타임의 클래스에서 Equals(Object) 메서드 오버로드를 호출하면, Equals(Object)를 재정의하지 않는 클래스에 대한 기본 동작을 제공합니다. 이는 .NET이 Windows 런타임에 대해 제공하는 지원의 일부입니다( Windows 스토어 앱 및 Windows 런타임에 대한 .NET 지원 참조). Windows 런타임의 클래스는 Object를 상속되지 않으며 현재 Equals(Object) 메서드를 구현하지 않습니다. 그러나 C# 또는 Visual Basic 코드에서 사용할 때 ToString, Equals(Object), GetHashCode 방법이 있는 것처럼 보이며, .NET은 이러한 메서드에 대한 기본 동작을 제공합니다.
비고
C# 또는 Visual Basic으로 작성된 Windows 런타임 클래스는 Equals(Object) 메서드 오버로드를 재정의할 수 있습니다.
발신자에 대한 참고 사항
파생 클래스는 값의 동등성을 구현하기 위해 Object.Equals(Object) 메서드를 재정의하는 경우가 많습니다. 형식은 종종 Equals 인터페이스를 구현함으로써 IEquatable<T> 메서드에 대해 강력한 형식의 추가 오버로드를 제공합니다. 메서드 Equals를 호출하여 같음을 테스트할 때, 현재 인스턴스가 Object.Equals를 재정의하는지 여부와 특정 Equals 메서드 호출이 해결되는 방법을 이해해야 합니다. 그렇지 않으면 의도한 것과 다른 같음 테스트를 수행하고 메서드가 예기치 않은 값을 반환할 수 있습니다.
다음 예제에서 이에 대해 설명합니다. 동일한 문자열을 사용하여 세 StringBuilder 개의 개체를 인스턴스화한 다음 메서드를 Equals 네 번 호출합니다. 첫 번째 메서드 호출은 true를 반환하고, 나머지 세 번은 false를 반환합니다.
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): {sb1.Equals(sb2)}");
Console.WriteLine($"((Object) sb1).Equals(sb2): {((Object) sb1).Equals(sb2)}");
Console.WriteLine($"Object.Equals(sb1, sb2): {Object.Equals(sb1, sb2)}");
Object sb3 = new StringBuilder("building a string...");
Console.WriteLine($"\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
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 개체가 Object로 캐스팅될 때, StringBuilder 인스턴스가 Object 형식의 변수에 할당될 때, 그리고 Object.Equals(Object, Object) 메서드에 두 개의 StringBuilder 개체가 전달될 때, 기본 Object.Equals(Object) 메서드가 호출됩니다.
StringBuilder 참조 형식이므로 두 StringBuilder 개체 ReferenceEquals 를 메서드에 전달하는 것과 같습니다. 세 StringBuilder 개체 모두 동일한 문자열을 포함하지만 세 개의 고유 개체를 참조합니다. 따라서 이러한 세 가지 메서드 호출은 반환됩니다 false.
메서드를 호출 ReferenceEquals 하여 참조 같음을 위해 현재 개체를 다른 개체와 비교할 수 있습니다. Visual Basic에서는 is 키워드를 사용할 수도 있습니다(예: If Me Is otherObject Then ...).
상속자에 대한 참고 사항
고유한 형식을 정의할 때 해당 형식은 기본 형식의 메서드에 Equals 정의된 기능을 상속합니다. 다음 표에서는 .NET의 Equals 주요 형식 범주에 대한 메서드의 기본 구현을 나열합니다.
| 유형 범주 | 평등의 정의 방식 | 코멘트 |
|---|---|---|
| 에서 직접 파생된 클래스 Object | Object.Equals(Object) | 참조 같음; 호출 Object.ReferenceEquals에 해당합니다. |
| 구조 | ValueType.Equals | 값 같음; 직접 바이트 바이트 비교 또는 리플렉션을 사용한 필드별 비교 중 하나. |
| 열거 | Enum.Equals | 값은 동일한 열거형 형식과 동일한 기본 값을 가져야 합니다. |
| 대리인 | MulticastDelegate.Equals | 대리자는 유형이 동일하고 호출 목록이 일치해야 합니다. |
| 인터페이스 | Object.Equals(Object) | 참조 동등성 |
값 형식의 경우 항상 Equals를 재정의해야 합니다. 왜냐하면 리플렉션에 의존하는 동등성 테스트는 성능이 떨어지기 때문입니다. 기본 구현 Equals을 재정의하여 참조 형식에 대해 참조 동일성이 아닌 값 동일성을 테스트하고, 값 동일성의 정확한 의미를 참조 형식에서 정의할 수도 있습니다. 두 개체가 동일한 인스턴스가 아니더라도 값이 같으면 Equals 구현은 true을 반환합니다. 형식의 구현자는 개체의 값을 구성하는 항목을 결정하지만 일반적으로 개체의 인스턴스 변수에 저장된 데이터의 일부 또는 전부입니다. 예를 들어, String 객체의 값은 문자열의 문자에 기반합니다. String.Equals(Object) 메서드는 Object.Equals(Object) 메서드를 재정의하여 동일한 순서로 동일한 문자를 포함하는 두 문자열 인스턴스에 대해 true을 반환합니다.
다음 예제는 값 같음을 테스트하기 위해 Object.Equals(Object) 메서드를 어떻게 재정의하는지를 보여줍니다. 클래스 Equals의 메서드 Person를 재정의합니다. 같음의 기본 클래스 구현을 수락한 경우 Person 두 Person 개체는 단일 개체를 참조하는 경우에만 동일합니다. 그러나 이 경우 두 Person 개체는 Person.Id 속성값이 같을 때 동일합니다.
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) 메서드의 모든 구현에 대해 참이어야 합니다. 목록에서 xyznull이 아닌 개체 참조를 나타냅니다.
x.Equals(x)은(는)true을(를) 반환합니다.x.Equals(y)는y.Equals(x)와 동일한 값을 반환합니다.x.Equals(y)는true와x가 둘 다y인 경우NaN를 반환합니다.(x.Equals(y) && y.Equals(z))가true를 반환하면x.Equals(z)가true를 반환합니다.x.Equals(y)및x가 참조하는 개체가 수정되지 않는 한,y의 연속 호출은 동일한 값을 반환합니다.x.Equals(null)은(는)false을(를) 반환합니다.
구현은 예외를 발생시켜서는 안 되며, 항상 값을 반환해야 합니다. 예를 들어, obj이 null인 경우, Equals 메서드는 false를 반환해야 하며, ArgumentNullException을(를) 발생시키지 않아야 합니다.
오버라이드할 때 다음 지침을 따르십시오:Equals(Object)
구현하는 IComparable 형식은 Equals(Object)을 재정의해야 합니다.
Equals(Object)를 재정의하는 형식은 GetHashCode 또한 재정의해야 합니다. 그렇지 않으면 해시 테이블이 제대로 작동하지 않을 수 있습니다.
IEquatable<T> 인터페이스를 구현하여 같음을 위한 강력한 형식의 테스트를 지원하는 것을 고려하십시오. IEquatable<T>.Equals 구현 시 Equals와 일치하는 결과를 반환해야 합니다.
프로그래밍 언어가 연산자 오버로드를 지원하고 지정된 형식에 대해 동등 연산자를 오버로드하는 경우, 해당 동등 연산자와 동일한 결과를 반환하도록 Equals(Object) 메서드를 재정의해야 합니다. 이렇게 하면 사용하는 Equals 클래스 라이브러리 코드(예: ArrayList 및 Hashtable)가 애플리케이션 코드에서 같음 연산자를 사용하는 방식과 일치하는 방식으로 동작하도록 할 수 있습니다.
참조 형식에 대한 지침
Equals(Object)이(가) 참조 유형에 대해 재정의될 때 다음 지침이 적용됩니다.
타입의 의미 체계가 해당 타입이 어떤 값(들)을 나타낸다는 사실을 기반으로 한다면, Equals를 재정의하는 것이 좋습니다.
대부분의 참조 형식은 같음 연산자를 오버로드하면 안 됩니다, 비록 Equals를 재정의할지라도. 그러나 복소수 형식과 같은 값 의미 체계를 갖도록 의도된 참조 형식을 구현하는 경우 같음 연산자를 재정의해야 합니다.
변경 가능한 참조 유형에서는 Equals를 오버라이드해서는 안 됩니다. 이는 이전 섹션에서 설명한 대로 Equals을(를) 재정의하려면 GetHashCode 메서드도 재정의해야 하기 때문입니다. 즉, 변경 가능한 참조 형식 인스턴스의 해시 코드는 수명 동안 변경될 수 있으므로 해시 테이블에서 개체가 손실될 수 있습니다.
값 형식에 대한 지침
값 타입 Equals(Object) 를 재정의하는 경우 다음 지침이 적용됩니다.
값이 참조 형식인 하나 이상의 필드를 포함하는 값 형식을 정의하는 경우 Equals(Object)을(를) 재정의해야 합니다. 제공된 Equals(Object) 구현은 ValueType 필드가 모두 값 형식인 값 형식에 대해 바이트 바이트 비교를 수행하지만 리플렉션을 사용하여 필드에 참조 형식이 포함된 값 형식의 필드별 비교를 수행합니다.
재정의 Equals를 하고 당신의 개발 언어가 연산자 오버로드를 지원하는 경우 같음 연산자를 오버로드해야 합니다.
당신은 IEquatable<T> 인터페이스를 구현해야 합니다. 강력한 형식의 IEquatable<T>.Equals 메서드를 호출하면
obj인수가 박싱되지 않습니다.
예시
다음 예제는 값 같음을 제공하기 위해 Point 메서드를 재정의하는 Equals 클래스를 보여주며, Point3D로부터 파생된 Point 클래스를 설명합니다.
Point는 값 같음을 테스트하기 위해 Object.Equals(Object)를 재정의하므로, Object.Equals(Object) 메서드는 호출되지 않습니다. 그러나 Point3D.Equals는 값 같음을 제공하는 방식으로 Point.Equals를 구현하므로 Point가 Object.Equals(Object)를 호출합니다.
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($"{point2D} = {point3Da}: {point2D.Equals(point3Da)}");
Console.WriteLine($"{point2D} = {point3Db}: {point2D.Equals(point3Db)}");
Console.WriteLine($"{point3Da} = {point3Db}: {point3Da.Equals(point3Db)}");
Console.WriteLine($"{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 인수가 obj이 아니고 이 개체와 동일한 형식의 인스턴스를 참조하는지 확인합니다. 확인 중 하나가 실패하면 메서드가 반환됩니다 false.
메서드는 Point.Equals 메서드를 GetType 호출하여 두 개체의 런타임 형식이 동일한지 여부를 확인합니다. 메서드가 C#에서 양식 obj is Point 확인을 사용하거나 Visual Basic에서 TryCast(obj, Point) 확인을 사용하는 경우, obj가 Point의 파생 클래스의 인스턴스일지라도 현재 인스턴스 및 obj가 동일한 런타임 형식이 아니더라도 확인 결과는 true를 반환합니다. 두 개체가 동일한 형식임을 확인한 후 메서드는 형식 obj 으로 캐스팅 Point 되고 두 개체의 인스턴스 필드를 비교한 결과를 반환합니다.
Point3D.Equals에서 상속된 Point.Equals 메서드는 Object.Equals(Object)를 재정의하며 다른 작업이 수행되기 전에 호출됩니다.
Point3D는 봉인된 클래스(NotInheritableVisual Basic)이므로, C#의 obj is Point 형식이나 Visual Basic의 TryCast(obj, Point) 형식으로 확인하면 obj가 Point3D 객체인지 확인하기에 충분합니다.
Point3D 객체인 경우 Point 객체로 캐스팅되어 Equals의 기본 클래스 구현에 전달됩니다. 상속된 Point.Equals 메서드가 true 반환될 때만, 메서드는 파생 클래스에서 도입된 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($"{r1} = {r2}: {r1.Equals(r2)}");
Console.WriteLine($"{r1} = {r3}: {r1.Equals(r3)}");
Console.WriteLine($"{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은 연산자 오버로딩을 지원합니다. 형식이 같음 연산자를 오버로드하는 경우, 동일한 기능을 제공하기 위해 EqualsEquals(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($"{cmplx1} <> {cmplx2}: {cmplx1 != cmplx2}");
Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1.Equals(cmplx2)}");
cmplx2.re = 4.0;
Console.WriteLine($"{cmplx1} = {cmplx2}: {cmplx1 == cmplx2}");
Console.WriteLine($"{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#의 is 연산자 또는 Visual Basic의 TypeOf 연산자를 사용하여 obj 매개 변수의 형식을 확인할 수 있습니다.
.NET