2017-11-16 11 views
2

간단히 말하면 C# 6.0 설명서를 읽는 중입니다. 아래 코드는 "Implementing the IComparable Interfaces"항목입니다.IComparable 인터페이스 구현

내가 몇 가지를하지 않는 다음 IComparable.CompareTo 명시 적으로이 구현되는 이유는

  1. ? 이 CompareTo (하나의 암시 int CompareTo (Note other)의 또 다른 암시 적 과부하 될 경우 어떻게
  2. , 또 다른 하나의 암시 int CompareTo (object other)? 당신은 암시 IComparable을 구현할 수
public struct Note : IComparable<Note>, IEquatable<Note>, IComparable 
{ 
    int _semitonesFromA; 
    public int SemitonesFromA { get { return _semitonesFromA; } } 

    public Note (int semitonesFromA) 
    { 
    _semitonesFromA = semitonesFromA; 
    } 

    public int CompareTo (Note other) // Generic IComparable<T> 
    { 
    if (Equals (other)) return 0; // Fail-safe check 
    return _semitonesFromA.CompareTo (other._semitonesFromA); 
    } 

    int IComparable.CompareTo (object other) // Nongeneric IComparable 
    { 
    if (!(other is Note)) 
    throw new InvalidOperationException ("CompareTo: Not a note"); 
    return CompareTo ((Note) other); 
    } 

    public static bool operator < (Note n1, Note n2) 
    => n1.CompareTo (n2) < 0; 

    public static bool operator > (Note n1, Note n2) 
    => n1.CompareTo (n2) > 0; 

    public bool Equals (Note other) // for IEquatable<Note> 
    => _semitonesFromA == other._semitonesFromA; 

    public override bool Equals (object other) 
    { 
    if (!(other is Note)) return false; 
    return Equals ((Note) other); 
    } 

    public override int GetHashCode() => _semitonesFromA.GetHashCode(); 
    public static bool operator == (Note n1, Note n2) => n1.Equals (n2); 
    public static bool operator != (Note n1, Note n2) => !(n1 == n2); 
} 

답변

6

, 예. 그러나 근본적으로 당신이 시도 할 사용자가 Note을 다른 Note과 비교하지 못하게하십시오. IComparable 일 경우 기존 사용법이있을 수 있지만 Note 클래스에 대해 알고 있다면 직접 llow :

Note note = new Note(); 
Other other = new Other(); 
int result = note.CompareTo(other); 

항상 예외가 발생한다는 것을 알고 계시지 않으십니까? 기본적으로 비 제너릭 IComparable 인터페이스를 "다소 유산"이라고 간주하고 (유효한 용도가 있지만 ...), 명시 적으로 구현하여 사용하지 못하게하십시오.