ulong和long之间的不可能比较突然可能

时间:2012-07-26 23:56:37

标签: c# casting long-integer comparison-operators

我知道为什么不允许这样做:

ulong x = 0xFEDCBA9876543210;
long y = Int64.MaxValue;
Console.WriteLine(x < y);

显然,运行时无法将操作数隐式转换为其他类型或更大的类型以使比较有效。

  

运营商'&lt;'不能应用于'ulong'和'long'类型的操作数。

因此,这也是不允许的(使用MinValueconst):

ulong x = 0xFEDCBA9876543210;
const long y = Int64.MinValue;
Console.WriteLine(x < y);

然而,这是允许的(改为MaxValue):

ulong x = 0xFEDCBA9876543210;
const long y = Int64.MaxValue;
Console.WriteLine(x < y);

<接受ulonglong并没有超载,但我在Reflector中看到,这会将Int64.MaxValue静默转换为ulong。但这并不总是发生。它是如何工作的,以及这种不一致的原因是什么?

2 个答案:

答案 0 :(得分:3)

long y = Int64.MaxValue; if (x < y)...if (x < Int64.MaxValue)之间的一个重要区别是,在后一种情况下,如果需要,编译器实际上可以看到常量值。它可以看到实际的常量值适合ulong范围,因此隐式转换是可以的。

对于普通变量long y,编译器不能对y的运行时值进行任何假设。没关系,赋值语句只是一个陈述;编译器不跟踪分配给变量的值。

正如DarkGray所指出的,const var表现为一个常量,因为你告诉编译器它的值永远不会改变。

答案 1 :(得分:1)

const long在ulong范围内的值会无声地转换为const ulong。

这是允许的:

ulong x = 0xFEDCBA9876543210; 
const long y = Int64.MaxValue; 
Console.WriteLine(x < y); 

const ulong z = y;
相关问题