問(wèn)題描述
我知道在 C# 中使用 null 合并運(yùn)算符的標(biāo)準(zhǔn)方法是設(shè)置默認(rèn)值值.
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"
但是??
還能用來(lái)做什么?除了更簡(jiǎn)潔和更容易閱讀:
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
因此,很少有人知道空合并運(yùn)算符...
So given that fewer even know about null coalescing operator...
您是否將
??
用于其他用途?
??
是必需的,還是應(yīng)該使用三元運(yùn)算符(即大多數(shù)都熟悉)
Is ??
necessary, or should you just use the ternary operator (that
most are familiar with)
推薦答案
嗯,首先,它比標(biāo)準(zhǔn)的三元運(yùn)算符更容易鏈接:
Well, first of all, it's much easier to chain than the standard ternary operator:
string anybody = parm1 ?? localDefault ?? globalDefault;
對(duì)比
string anyboby = (parm1 != null) ? parm1
: ((localDefault != null) ? localDefault
: globalDefault);
如果可能為 null 的對(duì)象不是變量,它也能很好地工作:
It also works well if a null-possible object isn't a variable:
string anybody = Parameters["Name"]
?? Settings["Name"]
?? GlobalSetting["Name"];
對(duì)比
string anybody = (Parameters["Name"] != null ? Parameters["Name"]
: (Settings["Name"] != null) ? Settings["Name"]
: GlobalSetting["Name"];
這篇關(guān)于使用空合并運(yùn)算符的獨(dú)特方法的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!