return 内联 if 中的 ulong

return ulong in inline-if

有什么原因导致我不能使用下面的代码吗?

ulong test(int a, int b)
{
    return a == b ? 0 : 1;
}

它告诉我:

Cannot implicitly convert type 'int' to 'ulong'. An explicit conversion exists (are you missing a cast?)

以下将起作用:

ulong test(int a, int b)
{
    return false ? 0 : 1;
}

我知道如何解决这个问题。我只想知道原因。

谢谢。

这将起作用:

ulong test(int a, int b)
{
    return a == b ? 0UL : 1UL;
}

看,编译器根据数字的大小推断类型,所以如果你想要一个特定的类型,你必须给出后缀。请参阅此 MSDN page

的文字部分

编辑:正如我所指出的,这个问题并不是在寻找如何让它发挥作用的答案。我相信链接的 MSDN 文章中仍有一些价值。它提供的信息可以解释为什么失败案例不起作用,但不能解释为什么另一个案例通过。确实很有趣的问题。

类型为 int 的变量不能隐式转换为 ulong,因为 int 可以表示负值,而 ulong 不能。常量可以隐式转换,前提是常量表达式的值是非负数。

你的第二个例子是常量表达式。

我们来看看第二种方法生成的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

IL_0001 处,文字 1 被压入堆栈(因此表达式 return false ? 0 : 1; 在编译时被求值并作为常量嵌入到 IL 中)和在 IL_0002 这个文字被转换成一个 Int64

来自 MSDN:

A constant-expression (Section 7.15) of type int can be converted to type sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant-expression is within the range of the destination type.

由于1ulong数据类型的范围内,这样的转换总是会成功的。编译器知道这一点,因此执行隐式转换。