请参阅下面的代码,我从这里开始:https://ericlippert.com/2013/10/07/math-from-scratch-part-six-comparisons/
public int CompareTo(Natural x) { return CompareTo(this, x); }
public static bool operator <(Natural x, Natural y) { return CompareTo(x, y) < 0; }
public static bool operator >(Natural x, Natural y) { return CompareTo(x, y) > 0; }
public static bool operator <=(Natural x, Natural y) { return CompareTo(x, y) <= 0; }
public static bool operator >=(Natural x, Natural y) { return CompareTo(x, y) >= 0; }
public static bool operator ==(Natural x, Natural y) { return CompareTo(x, y) == 0; }
public static bool operator !=(Natural x, Natural y) { return CompareTo(x, y) != 0; }
public override bool Equals(object obj) { return CompareTo(this, obj as Natural) == 0; }
public bool Equals(Natural x) { return CompareTo(this, x) == 0; }
// negative means x < y
// positive means x > y
// zero means x == y
// two nulls are equal
// otherwise, null is always smaller
private static int CompareTo(Natural x, Natural y) {
if (ReferenceEquals(x, y))
return 0;
else if (ReferenceEquals(x, null))
return -1;
else if (ReferenceEquals(y, null))
return 1;
else if (ReferenceEquals(x, Zero))
return -1;
else if (ReferenceEquals(y, Zero))
return 1;
else if (x.head == y.head)
return CompareTo(x.tail, y.tail);
else if (x.head == ZeroBit)
return CompareTo(x.tail, y.tail) > 0 ? 1 : -1;
else
return CompareTo(x.tail, y.tail) < 0 ? -1 : 1;
}
变量零是什么意思?我假设它是这样声明和初始化的(基于评论所说的):
var Zero = zero means x == y;
为什么要将等于x引用到x == y和y引用x == y?
答案 0 :(得分:3)
Zero
可能是一个静态实例,例如:
public static readonly Natural Zero = new Natural(0);
至于为什么要将值与null
和其他值进行比较:您与null
进行比较,以便在涉及{{1}的检查中避免使用NullReferenceException
}或x.tail
,并允许对包含y.tail
个引用的列表进行排序,以使其正常工作,所有null
将转到开头或结尾(但是:始终如一)。您将null
与x
进行比较,因为:与任何对象进行比较时,任何对象都应报告“匹配”(返回y
),b:同时报告0
和{{1 {}}都是x
,我们应该还返回“匹配”y
。对null
和0
进行参考检查可以方便地解决这两种常见情况。