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

标签 c# operators

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

 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";

问号的所有用法是否相关或不同?它们分别是什么意思?

最佳答案

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

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

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

string? value = "bob"; 

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

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

关于c# - 问号在 C# 代码中意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43075113/

相关文章:

c# - Linq to SQL 按 2 个实体(父子)中的字段排序

c# - 使用 Selenium WebDriver C# 从下拉列表中选择一个值

c# - "Authentication failed because the remote party has closed the transport stream"使用 FluentFTP 通过 TLS/SSL 传输到/从 FTP 服务器时

c++ - 运算符顺序在这里

go - golang中的 bool 值没有异或运算符吗?

java.lang.Number 没有实现 "+"或任何其他运算符?

c# - 托管时 ASP.Net Com-InterOp Excel 生成问题

c# - 实体核心映射实体类型与连接表

java - 为什么模 3 效率低下?

java - 乘法时结果不同