gpt4 book ai didi

c# - `` 吗? ?`` 运营商使用短路?

转载 作者:太空狗 更新时间:2023-10-29 18:14:23 26 4
gpt4 key购买 nike

C# 中的 ?? 运算符在计算时是否使用短路?

var result = myObject ?? ExpressionWithSideEffects();

myObject为非空时,ExpressionWithSideEffects()的结果不会被使用,但是ExpressionWithSideEffects()会被完全跳过吗?

最佳答案

是的,它会短路。

这是在 LinqPad 中测试的片段:

string bar = "lol";
string foo = bar ?? string.Format("{2}", 1);
foo.Dump();
bar = null;
foo = bar ?? string.Format("{2}", 1);
foo.Dump();

第一个合并没有抛出异常,而第二个确实抛出异常(格式字符串无效)。

关于c# - `` 吗? ?`` 运营商使用短路?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3103557/

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