我现在正在Nutshell中阅读c#6.0这本书,下面的代码是关于“实现IComparable接口”的主题。
我没有得到一些东西:
IComparable.CompareTo
在那里明确实施?CompareTo
的另一个隐式重载(一个隐含的重载)会怎样
int CompareTo (Note other)
,另一个隐含int CompareTo (object other)
?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);
}
答案 0 :(得分:6)
你可以隐含地实施IComparable
,是的。但从根本上说,您希望阻止用户将Note
与其他Note
以外的任何内容进行比较。如果IComparable
,您可能会有遗留用法,但如果有任何关于Note
课程的直接知道,您就不想允许:
Note note = new Note();
Other other = new Other();
int result = note.CompareTo(other);
你知道这总会引发异常,为什么要允许呢?基本上,将非通用IComparable
接口视为&#34;有点遗留&#34; (有效用途,但......)并且不鼓励任何人明确地实施它。