【发布时间】:2021-12-14 22:46:22
【问题描述】:
我理解“CompareTo 比较实例和值(在我的代码中由 amountA - 实例和 amountB 值表示),它可能返回 1、-1 或 0,具体取决于我们对实例和值的了解。
谁能解释一下为什么它返回 1、-1 或 0?虽然我能用,但我想更好地理解这个方法。
谢谢!
请看下面我的 C# 代码//
if (Math.Round(amountA, 2).CompareTo(Math.Round(amountB, 2)) == 0)
{
return ("Plan " + planA.Name + " costs " + amountA) + " " + ("Plan " + planB.Name + " costs " + amountB) + " " + message3;
}
else if (amountA.CompareTo(amountB) > 0)
{
return ("Plan " + planA.Name + " costs " + amountA) + " " + ("Plan " + planB.Name + " costs " + amountB) + " " + message1;
}
else if (amountA.CompareTo(amountB) < 0)
{
return ("Plan " + planA.Name + " costs " + amountA) + " " + ("Plan " + planB.Name + " costs " + amountB) + " " + message2;
}
return "";
}
【问题讨论】: