问号在C#代码中意味着什么?

时间:2017-03-28 16:34:56

标签: c# operators

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

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

问号的所有用法是相关的还是不同的?他们每个人的意思是什么?

1 个答案:

答案 0 :(得分:11)

问号在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";

Null Coalescing Operator 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;