使用 和有什么区别??和 C# 中的 if not null 块?

What is the difference between using ?? and an if not null block in C#?

在 C# 中使用 ??if (foo == null) {...} else {...} 有区别吗?

?? 运算符只会评估您的值一次,您的版本可能会评估多次。

所以

var baz = foo ?? bar;

应该被评估为

var tmp = foo;
if(tmp == null)
{
    tmp = bar;
}
var baz = tmp;

foo 是函数或 属性 在 getter.

中有副作用时,这一点很重要
private int _counter1 = 0;
private int _counter2 = 0;

private string Example1()
{
    _counter1++;
    if(_counter1 % 2 == 0)
        return _counter1.ToString();
    else
        return null;
}

private string Example2()
{
    _counter2++;
    return _counter2.ToString();
}

每次执行 var result = Example1() ?? Example2() 时,_counter1 的值应该只增加 1,而 _counter2 的值应该每隔一次调用就增加。

//Equivalent if statement
var tmp = Example1();
if(tmp == null)
{
    tmp = Example2();
}
var result = tmp;