TOC

This article is currently in the process of being translated into Chinese (~71% done).

Operators:

The NULL coalescing operator

??运算符也叫做“空值判断综合运算符”,因为其允许只用一个表达式判断一个变量是否为空值,并在为空的情况下返回一个回滚值。无此运算符似乎也能轻易实现此操作,不过请看如下例子:

string userSuppliedName = null; 

if (userSuppliedName == null)
    Console.WriteLine("Hello, Anonymous!");
else
    Console.WriteLine("Hello," + userSuppliedName);

假设变量userSuppliedName是用户提供的,如,来自对话框或数据文件 - 反正是个可能导致结果值为空的来源。程序在使用此变量前必需进行为空检查,如,在显示此姓名前。

上例中,程序使用了经典的if-else模式,但如果使用空值判断综合运算符,可以很精简,一个表达式就行:

Console.WriteLine("Hello, " + (userSuppliedName ?? "Anonymous")); 

在此单个表达式中,如果userSuppliedName有值,编译器就使用该值 - 如果没能有值(为空),就使用表达式中提供的回滚值“Anonymous”。方便实用!

总结

空值判断综合运算符与所有的精简类运算符一样,是一个平衡代码精简与可读性的方式。有人觉得这些运算符可读性差,让代码难以理解,也有人喜欢其短小精悍。用与不用程序员自己决定!


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!