<??>符号在C#.NET中的含义是什么?

Bib*_*ath 8 .net c# symbols

可能重复:
什么是"??"运算符?

我看到一行代码表明 -

return (str ?? string.Empty).Replace(txtFind.Text, txtReplace.Text);
Run Code Online (Sandbox Code Playgroud)

我想知道这条线的确切含义(即??部分)..

Wil*_*den 19

它是null合并运算符:如果它是非null,则返回第一个参数,否则返回第二个参数.在您的示例中,str ?? string.Empty实际上用于为空字符串交换空字符串.

它对于可空类型特别有用,因为它允许指定默认值:

int? nullableInt = GetNullableInt();
int normalInt = nullableInt ?? 0;
Run Code Online (Sandbox Code Playgroud)

编辑: str ?? string.Empty可以根据条件运算符重写str != null ? str : string.Empty.如果没有条件运算符,则必须使用更详细的if语句,例如:

if (str == null)
{
    str = string.Empty;
}

return str.Replace(txtFind.Text, txtReplace.Text);
Run Code Online (Sandbox Code Playgroud)


Iga*_*nik 9

它被称为空合并运算符.它允许您有条件地从链中选择第一个非空值:

string name = null;
string nickname = GetNickname(); // might return null
string result = name ?? nickname ?? "<default>";
Run Code Online (Sandbox Code Playgroud)

值in result将是nicknameif 的值不为null,或者"<default>".