Equals()

public static bool ReferenceEquals(object left, object right);
public static bool Equals(object left, object right);
// 재정의하는 경우 IEquatable<T>를 구현해야 한다.
// (값에 고유의 의미 체계를 부여하기 위해 IStructuralEquality를 구현하기도 함)
public virtual bool Equals(object right);
// 주로 성능을 개선하기 위해 재정의
public static bool operator == (MyClass left, MyClass right);
  • 참조 타입의 경우, 참조 대상이 같으면 동일하다고 간주
  • 값 타입의 경우, 두 객체의 타입과 값의 내용이 일치해야만 동일한 객체로 판단
public static bool Equals(object left, object right)
{
    if (object.ReferenceEquals(left, right))
        return true;
 
    if (object.ReferenceEquals(left, null) ||
        object.ReferenceEquals(right, null))
        return false;
 
    return left.Equals(right);
}

동일성의 수학적 속성

  • 반사적 속성(reflexive property)
    • 어떤 객체든 자기 자신과는 항상 같아야 한다.
  • 대칭적 속성(symmetric property)
    • 동일성의 결과가 비교 순서와는 무관해야 한다.
  • 추이적 속성(transitive property)
    • if (a == b) and (b == c), a == c

 

IEquatable<T>

public class MyClass : IEquatable<MyClass>
{
    public override bool Equals(object other)
    {
        // C# 메서드 내에서 this는 절대 null이 될 수 없다.
        if (object.ReferenceEquals(right, null))
            return false;

        if (object.ReferenceEquals(this, other))
            return true;

        if (this.GetType() != other.GetType())
            return false;

        return this.Equals(other as MyCalss)
    }

    // IEquatable<MyClass>
    public bool Equals(MyClass other)
    {
        ;
    }
}

'.NET > C#' 카테고리의 다른 글

Concurrency (동시성)  (0) 2023.08.16
Marshaling: 복사 및 고정  (0) 2021.10.15
Array Marshaling  (0) 2021.10.15
Comparisons and Sorts  (0) 2021.10.15
Debugging Tips  (0) 2021.09.15

+ Recent posts