什么打印这个程序?
static void Main(string[] args)
{
int? other = null;
int value = 100 + other ?? 0;
Console.WriteLine(value);
}
我知道我脑子里没有语言规范。但是它打印 0 而不是 100 仍然令人惊讶。对于这种奇怪的行为是否有合理的解释?
当我使用大括号时,我得到了正确的结果。
static void Main(string[] args)
{
int? other = null;
int value = 100 + (other ?? 0);
Console.WriteLine(value);
}
最佳答案
当前表达式的计算结果为:
(100 + other) ?? 0;
other
的值为null,一个数字加上null还是null。所以表达式输出 0。
在您的第二个示例中,您首先评估 null 检查,然后添加 100。
关于c# - 可空结果令人惊讶,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33625941/