gpt4 book ai didi

c# - 实现 IComparable 接口(interface)

转载 作者:行者123 更新时间:2023-11-30 20:16:56 26 4
gpt4 key购买 nike

我现在正在阅读《c#6.0 in a Nutshell》这本书,下面的代码主题是“实现 IComparable 接口(interface)”。

我没有得到一些东西:

  1. 为什么 IComparable.CompareTo 在那里显式实现?
  2. 如果这只是 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);
}

最佳答案

可以隐式实现IComparable,是的。但从根本上说,您想要阻止用户将 Note 与另一个 Note 以外的任何内容进行比较。如果 IComparable,您可能有遗留用法,但如果有任何人直接知道 Note 类,您不希望允许:

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

您知道这总是会引发异常,那么为什么要允许它呢?基本上,将非通用 IComparable 接口(interface)视为“有点遗留”(有有效用途,但是......)并通过明确实现它来阻止任何人使用它。

关于c# - 实现 IComparable 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47327044/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com