Dan*_*ker 6 c# casting comparison-operators long-integer
我知道为什么不允许这样做:
ulong x = 0xFEDCBA9876543210;
long y = Int64.MaxValue;
Console.WriteLine(x < y);
Run Code Online (Sandbox Code Playgroud)
显然,运行时无法将操作数隐式转换为其他类型或更大的类型以使比较起作用.
运算符'<'不能应用于'ulong'和'long'类型的操作数.
所以,这也是不允许的(带MinValue和const):
ulong x = 0xFEDCBA9876543210;
const long y = Int64.MinValue;
Console.WriteLine(x < y);
Run Code Online (Sandbox Code Playgroud)
然而,这是允许的(MaxValue相反):
ulong x = 0xFEDCBA9876543210;
const long y = Int64.MaxValue;
Console.WriteLine(x < y);
Run Code Online (Sandbox Code Playgroud)
<接受a ulong并没有过载long,但是我看到Reflector它会默默地转换Int64.MaxValue为a ulong.但这并不总是发生.它是如何工作的,以及这种不一致的原因是什么?
long y = Int64.MaxValue; if (x < y)...和之间的一个很大的区别if (x < Int64.MaxValue)是,在后一种情况下,编译器实际上可以根据需要看到常量值。可以看到实际的常量值在 ulong 范围内,因此隐式转换是可以的。
对于普通变量long y,编译器无法对 y 的运行时值做出任何假设。不要介意赋值语句只是一个语句;编译器不会跟踪分配给变量的值。
正如 DarkGray 所指出的, const var 的行为就像常量,因为您已经告诉编译器它的值永远不会改变。