推荐答案
// www.javascriptcn.com code example // 空合并运算符 (??) 示例 string name = null; string displayName = name ?? "Guest"; Console.WriteLine(displayName); // 输出: Guest // 空条件运算符 (?.) 示例 Person person = null; string personName = person?.Name; Console.WriteLine(personName); // 输出: (空)
本题详细解读
空合并运算符 (??)
空合并运算符 (??) 用于处理可能为 null 的值。如果左侧的操作数为 null,则返回右侧的操作数;否则返回左侧的操作数。这个运算符通常用于为可能为 null 的变量提供默认值。
语法:
result = leftOperand ?? rightOperand;
示例:
string name = null; string displayName = name ?? "Guest"; Console.WriteLine(displayName); // 输出: Guest
在这个例子中,name 是 null,因此 ?? 运算符返回右侧的操作数 "Guest",并将其赋值给 displayName。
空条件运算符 (?.)
空条件运算符 (?.) 用于在访问对象的成员之前检查对象是否为 null。如果对象为 null,则整个表达式的结果为 null,而不会抛出 NullReferenceException 异常。
语法:
result = object?.Member;
示例:
Person person = null; string personName = person?.Name; Console.WriteLine(personName); // 输出: (空)
在这个例子中,person 是 null,因此 ?. 运算符不会尝试访问 Name 属性,而是直接返回 null,并将其赋值给 personName。
结合使用
空合并运算符和空条件运算符可以结合使用,以提供更简洁和安全的代码。
示例:
Person person = null; string displayName = person?.Name ?? "Unknown"; Console.WriteLine(displayName); // 输出: Unknown
在这个例子中,如果 person 是 null 或者 person.Name 是 null,?. 运算符会返回 null,然后 ?? 运算符会返回 "Unknown" 作为默认值。