gpt4 book ai didi

c# - 可空结果令人惊讶

转载 作者:太空狗 更新时间:2023-10-30 00:10:09 26 4
gpt4 key购买 nike

什么打印这个程序?

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/

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