我见过类似以下不相关的代码:
Console.Write(myObject?.ToString());
return isTrue ? "Valid" : "Lie";
return myObject ?? yourObject;
int? universalAnswer = 42;
问号的所有用法是相关的还是不同的?他们每个人的意思是什么?
答案 0 :(得分:11)
问号在C#中具有不同的含义,具体取决于上下文。
空条件运算符(MSDN,What does the question mark in member access mean in C#?)
Console.Write(myObject?.Items?[0].ToString());
条件运算符/三元运算符(MSDN,Benefits of using the conditional ?: (ternary) operator)
return isTrue ? "Valid" : "Lie";
Null Coalescing Operator (MSDN,What do two question marks together mean in C#?)
return myObject ?? yourObject;
可空类型(MSDN,What is the purpose of a question mark after a type (for example: int? myVariable)?)
int? universalAnswer = 42;