【发布时间】:2023-04-01 06:58:01
【问题描述】:
考虑以下代码:
namespace ConsoleApplication1 {
class Program
{
static void Main(string[] args)
{
Console.WriteLine(100.CompareTo(200)); // prints -1
Console.WriteLine(((decimal)100).CompareTo((decimal)200)); // prints -1
Console.WriteLine(((short)100).CompareTo((short)200)); // prints -100
Console.WriteLine(((float)100).CompareTo((float)200)); // prints -1
Console.ReadKey();
}
}
}
我的问题是,Int16 上的 CompareTo 方法返回 -1、0 和 1 以外的值是否有任何具体原因?
ILSpy 显示它是这样实现的
public int CompareTo(short value)
{
return (int)(this - value);
}
而该方法是以这种方式在 Int32 上实现的
public int CompareTo(int value)
{
if (this < value)
{
return -1;
}
if (this > value)
{
return 1;
}
return 0;
}
【问题讨论】:
标签: .net compareto design-decisions