C# 中的 ?. 运算符
什么是 ?. 运算符?
?. 运算符(也称为空合并运算符)是一个 C# 运算符,用于安全地访问可能为 null 的属性或方法。
如何使用 ?. 运算符?
要使用 ?. 运算符,请将它放置在可能为 null 的属性或方法之前。如果属性或方法不为 null,运算符将返回其值。否则,它将返回 null。
例如:
<code class="csharp">Person? person = null; // person 可能为 null string name = person?.Name; // 如果 person 不为 null,则返回 name 属性;否则,返回 null</code>
?. 运算符的好处:
使用 ?. 运算符的主要好处是:
提高代码安全性:通过防止在 null 值上访问属性或方法,它有助于避免 NullReferenceException。 簡化代碼:無需檢查 null 並在代碼中使用嵌套 if 語句。 提高可讀性:?. 运算符使代码更易于阅读和理解。示例:
以下示例演示了如何在 C# 中使用 ?. 运算符:
<code class="csharp">class Person
{
public string Name { get; set; }
}
Person? person = null;
// 使用 ?. 运算符安全地访问 Name 属性
string name = person?.Name;
// 如果 person 不为 null,则打印 name;否则,打印 "Person is null"
Console.WriteLine(name ?? "Person is null");</code>输出:
<code>Person is null</code>
