为什么的CompareTo短期这种方式来实现? [英] Why is CompareTo on short implemented this way?
问题描述
考虑以下code:
命名空间ConsoleApplication1 {
类节目
{
静态无效的主要(字串[] args)
{
Console.WriteLine(100.CompareTo(200)); //输出-1
Console.WriteLine(((十进制)100).CompareTo((十进制)200)); //输出-1
Console.WriteLine(((短)100).CompareTo((短)200)); //输出-100
Console.WriteLine(((浮点)100).CompareTo((浮点)200)); //输出-1
Console.ReadKey();
}
}
}
我的问题是,是否有任何具体原因上的Int16的的CompareTo方法会返回值以外-1,0和1?的
ILSpy显示它是这样实现
公众诠释的CompareTo(short值)
{
返程(INT)(本 - 值);
}
而该方法implented上的Int32这样
公众诠释的CompareTo(int值)
{
如果(该<值)
{
返回-1;
}
如果(这种>值)
{
返回1;
}
返回0;
}
所不同的是,短
,有没有机会,结果四溢。例如, short.MinValue - (短)1
仍为负值 - 而 int.MinValue - 1
是 int.MaxValue
。
在换句话说,具体原因是,你可以逃脱的快捷与短
(没有双关语意),而相同的快捷方式无法与<工作code> INT 。你绝对不应该的需要的<一个href="http://msdn.microsoft.com/en-us/library/43hc6wht.aspx"><$c$c>IComparable<T>.CompareTo$c$c>实现返回-1,0或1。该文档是pretty的清楚,结果是唯一有意义的是负数,零或正条款。
Consider the following code:
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();
}
}
}
My question is, are there any specific reasons the CompareTo-method on Int16 returns values other than -1, 0 and 1?
ILSpy shows it is implemented this way
public int CompareTo(short value)
{
return (int)(this - value);
}
whereas the method is implented on Int32 this way
public int CompareTo(int value)
{
if (this < value)
{
return -1;
}
if (this > value)
{
return 1;
}
return 0;
}
The difference is that for short
, there's no chance of the result overflowing. For instance, short.MinValue - (short) 1
is still negative - whereas int.MinValue - 1
is int.MaxValue
.
In other words, the specific reason is that you can get away with a shortcut with short
(no pun intended) whereas the same shortcut doesn't work with int
. You should definitely not require IComparable<T>.CompareTo
implementations to return -1, 0 or 1. The documentation is pretty clear that the result is only meaningful in terms of being negative, zero, or positive.
这篇关于为什么的CompareTo短期这种方式来实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!