Mar*_*ner 6 c# ternary-operator conditional-operator ulong
我有什么理由不能使用以下代码吗?
ulong test(int a, int b)
{
return a == b ? 0 : 1;
}
Run Code Online (Sandbox Code Playgroud)
它告诉我:
Cannot implicitly convert type 'int' to 'ulong'. An explicit conversion exists (are you missing a cast?)
Run Code Online (Sandbox Code Playgroud)
以下将有效:
ulong test(int a, int b)
{
return false ? 0 : 1;
}
Run Code Online (Sandbox Code Playgroud)
我知道如何解决这个问题.我只是想知道原因.
谢谢.
我们看一下第二种方法生成的IL代码:
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: conv.i8
IL_0003: stloc.0
IL_0004: br.s IL_0006
IL_0006: ldloc.0
IL_0007: ret
Run Code Online (Sandbox Code Playgroud)
atIL_0001文字1被压入堆栈(因此表达式return false ? 0 : 1;在编译时计算并作为常量嵌入到 IL 中),并且 atIL_0002此文字被转换为Int64.
来自 MSDN:
如果常量表达式的值在目标类型的范围内,则 int 类型的常量表达式(第 7.15 节)可以转换为 sbyte、byte、short、ushort、uint 或 ulong 类型。
由于1是在数据类型的范围内ulong,这样的转换总是会成功。编译器知道这一点,因此执行隐式转换。