【问题标题】:What does a question mark mean in C# code? [duplicate]问号在 C# 代码中是什么意思? [复制]
【发布时间】:2017-08-21 20:31:24
【问题描述】:

我见过类似以下不相关行的代码:

 Console.Write(myObject?.ToString());
 return isTrue ? "Valid" : "Lie";
 return myObject ?? yourObject;
 int? universalAnswer = 42;

在 C#8+ 中似乎还有更多类似

 public static Delegate? Combine(params Delegate?[]? delegates)...
 string? value = "bob";

问号的所有用法都是相关的还是不同的?分别是什么意思?

【问题讨论】:

  • @DavidG 有点……原来stackoverflow.com/questions/43074622/… 没有可搜索的答案。我不确定关闭为 4 的副本是否是正确的解决方案 - 几天后会看到搜索引擎如何处理它。
  • @DavidG 好点 - 我没有注意到自答界面是否有 CW 选项 - 更改为 CW。
  • 很久以前有一个选项可以将问题/答案标记为社区 wiki。喜欢NullReferenceException 主题。现在找不到这个选项..
  • 我想知道帖子是否应该被这个帖子所欺骗?
  • @SergeyBerezovskiy 只有答案可以标记为 CW,并且只能由回答者或 mod 标记。 Questions can't be done by anyone but a mod

标签: c# operators


【解决方案1】:

问号在 C# 中具有不同的含义,具体取决于上下文。

空条件运算符MSDNWhat does the question mark in member access mean in C#?

Console.Write(myObject?.Items?[0].ToString());

条件运算符/三元运算符MSDNBenefits of using the conditional ?: (ternary) operator

return isTrue ? "Valid" : "Lie";

空合并运算符MSDNWhat do two question marks together mean in C#?

return myObject ?? yourObject;

可空值类型MSDNWhat is the purpose of a question mark after a type (for example: int? myVariable)?

int? universalAnswer = 42;

Nullable Reference Types C# 8 添加了可空引用类型和更多选项来添加问号(它还提供了放置解释标记的新位置 - null!”是 null-forgiving operator):

可空字符串(请记住string 是引用类型,其行为类似于值类型):

string? value = "bob"; 

可空引用对象的可空数组 - What is the ?[]? syntax in C#?

public static Delegate? Combine(Delegate?[]? delegates)

【讨论】:

  • 请问如果默认情况下可以包含(?)null,为什么有人将字符串设置为Nullable?是因为Nullable<T> 的特权/功能,例如.HasValue
猜你喜欢
  • 2014-07-28
  • 2019-06-08
  • 1970-01-01
  • 2015-10-08
  • 2013-05-15
  • 2018-06-23
  • 2013-10-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多