【问题标题】:What does <??> symbol mean in C#.NET? [duplicate]<??> 符号在 C#.NET 中的含义是什么? [复制]
【发布时间】:2011-01-18 09:37:29
【问题描述】:

可能重复:
What is the “??” operator for?

我看到了一行代码 -

return (str ?? string.Empty).Replace(txtFind.Text, txtReplace.Text);

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

【问题讨论】:

标签: c# .net symbols


【解决方案1】:

它是null coalescing operator:如果它不为null,则返回第一个参数,否则返回第二个参数。在您的示例中,str ?? string.Empty 本质上是用于将空字符串交换为空字符串。

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

int? nullableInt = GetNullableInt();
int normalInt = nullableInt ?? 0;

编辑: str ?? string.Empty 可以根据条件运算符重写为str != null ? str : string.Empty。如果没有条件运算符,您将不得不使用更冗长的 if 语句,例如:

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

return str.Replace(txtFind.Text, txtReplace.Text);

【讨论】:

  • 你能用详细的语法解释str ?? string.Empty吗?我的意思是用详细的语法替换这一行。 :)
【解决方案2】:

它被称为null coalescing operator。它允许您有条件地从链中选择第一个非空值:

string name = null;
string nickname = GetNickname(); // might return null
string result = name ?? nickname ?? "<default>";

result 中的值将是nickname 的值(如果它不为空),或者是"&lt;default&gt;"

【讨论】:

    【解决方案3】:

    相当于

    (str == null ? string.Empty : str)
    

    【讨论】:

    • 在这种特殊情况下是这样,但是如果您用任意表达式替换str,它会变得更加复杂 - 因为该表达式只会被计算一次。
    • 除了像这样的简单设置之外,我从未在任何设置中使用空合并运算符,所以我不确定您的意思。你介意发布一个你所指的例子吗?
    • Jon 的意思是,如果你说 F() ? G(),这与 (F() == null ? G() : F()) 不完全等效,因为那个东西调用了 F() 两次。它实际上更像是做一个隐式 temp = F() 然后计算 temp == null ? G():温度。实际上这也不对,因为事情变得复杂取决于运算符两侧的确切类型。我们也可能会在其中插入演员表。
    【解决方案4】:

    ??运算符说返回非空值。所以,如果你有以下代码:

    string firstName = null; 
    
    string personName = firstName ?? "John Doe"; 
    

    上面的代码将返回“John Doe”,因为 firstName 的值为空。

    就是这样!

    【讨论】:

      【解决方案5】:
      str ?? String.Empty
      

      可以写成:

      if (str == null) {
          return String.Empty;
      } else {
          return str;
      }
      

      或作为三元语句:

      str == null ? str : String.Empty;
      

      【讨论】:

      • 正如 Jon Skeet 在较早的答案中添加的那样,您的语句仅在简单情况下是等效的 - str 表达式仅使用 ?? 运算符评估一次。
      猜你喜欢
      • 2012-10-15
      • 2015-07-16
      • 2016-04-11
      • 2011-09-18
      • 2015-07-14
      • 1970-01-01
      • 2013-03-11
      • 2021-02-09
      • 1970-01-01
      相关资源
      最近更新 更多