gpt4 book ai didi

c# - ulong 和 long 之间不可能的比较突然成为可能

转载 作者:太空狗 更新时间:2023-10-29 21:45:59 24 4
gpt4 key购买 nike

我知道为什么这是不允许的:

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

显然,运行时无法将任一操作数隐式转换为其他类型或更大的类型来进行比较。

Operator '<' cannot be applied to operands of type 'ulong' and '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.MaxValueulong .但这并不总是发生。它是如何工作的,造成这种不一致的原因是什么?

最佳答案

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

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

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

关于c# - ulong 和 long 之间不可能的比较突然成为可能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11679708/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com