实现IComparable接口

时间:2017-11-16 10:19:39

标签: c# .net icomparable

我现在正在Nutshell中阅读c#6.0这本书,下面的代码是关于“实现IComparable接口”的主题。

我没有得到一些东西:

  1. 为什么IComparable.CompareTo在那里明确实施?
  2. 如果只是CompareTo的另一个隐式重载(一个隐含的重载)会怎样 int CompareTo (Note other),另一个隐含int CompareTo (object other)
  3. 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);
    }
    

1 个答案:

答案 0 :(得分:6)

可以隐含地实施IComparable,是的。但从根本上说,您希望阻止用户将Note与其他Note以外的任何内容进行比较。如果IComparable,您可能会有遗留用法,但如果有任何关于Note课程的直接知道,您就不想允许:

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

你知道这总会引发异常,为什么要允许呢?基本上,将非通用IComparable接口视为&#34;有点遗留&#34; (有效用途,但......)并且不鼓励任何人明确地实施它。