为什么CompareTo简称以这种方式实现?

slo*_*oth 5 .net compareto design-decisions

请考虑以下代码:

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();
        }
    } 
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,Int16上的CompareTo方法返回除-1,0和1以外的值有什么特殊原因吗?

ILSpy显示它以这种方式实现

public int CompareTo(short value)
{
    return (int)(this - value);
}
Run Code Online (Sandbox Code Playgroud)

而这种方法是以这种方式在Int32上实现的

public int CompareTo(int value)
{
    if (this < value)
    {
        return -1;
    }
    if (this > value)
    {
        return 1;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 13

不同之处在于short,结果不会溢出.举例来说,short.MinValue - (short) 1仍然是负的-而int.MinValue - 1int.MaxValue.

换句话说,具体原因是您可以使用快捷方式short(没有双关语),而相同的快捷方式不起作用int.你绝对不应该要求 IComparable<T>.CompareTo实现返回-1,0或1.文档很清楚,结果只有在为负,零或正方面时才有意义.


Mar*_*ell 5

那么,你应该只有真正检查就签收反正,但原因:我猜int等会有溢/包(处理2大的量级的数字时),这将扭转的迹象,这意味着它的风险必须检查的经营者.

我宁愿它是一致的,但它似乎不是一个问题.更可能是非典型但在记录的API内的优化.特别是,short在这里进行优化并不会感觉它会得到大量的使用(我使用 short,但不是我一样多int).