簡體   English   中英

使用??有什么區別? 在C#中是否為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是在吸氣劑中具有副作用的函數或屬性時,這點很重要。

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() var result = Example1() ?? Example2() _ _counter1的值_counter1應增加一個,而_counter2的值_counter2應在其他所有調用中增加。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM