我知道在 C# 中使用 null 合并运算符的标准方法是设置默认值值.
I know the standard way of using the null coalescing operator in C# is to set default values.
string nobody = null;
string somebody = "Bob Saget";
string anybody = "";
anybody = nobody ?? "Mr. T"; // Returns Mr. T
anybody = somebody ?? "Mr. T"; // Returns "Bob Saget"
但是??
还能用来做什么?除了更简洁和更容易阅读:
But what else can ??
be used for? It doesn't seem as useful as the ternary operator, apart from being more concise and easier to read than:
nobody = null;
anybody = nobody == null ? "Bob Saget" : nobody; // Returns Bob Saget
因此,很少有人知道空合并运算符...
So given that fewer even know about null coalescing operator...
您是否将 ??
用于其他用途?
??
是必需的,还是应该使用三元运算符(即大多数都熟悉)
Is ??
necessary, or should you just use the ternary operator (that
most are familiar with)
嗯,首先,它比标准的三元运算符更容易链接:
Well, first of all, it's much easier to chain than the standard ternary operator:
string anybody = parm1 ?? localDefault ?? globalDefault;
对比
string anyboby = (parm1 != null) ? parm1
: ((localDefault != null) ? localDefault
: globalDefault);
如果可能为 null 的对象不是变量,它也能很好地工作:
It also works well if a null-possible object isn't a variable:
string anybody = Parameters["Name"]
?? Settings["Name"]
?? GlobalSetting["Name"];
对比
string anybody = (Parameters["Name"] != null ? Parameters["Name"]
: (Settings["Name"] != null) ? Settings["Name"]
: GlobalSetting["Name"];
这篇关于使用空合并运算符的独特方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!