独特的方式使用空合并运算符 [英] Unique ways to use the Null Coalescing operator

查看:165
本文介绍了独特的方式使用空合并运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在C#中使用空合并运算符的标准方法是设置默认值。

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:

string anybody = parm1 ?? localDefault ?? globalDefault;

VS

string anyboby = (parm1 != null) ? parm1 
               : ((localDefault != null) ? localDefault 
               : globalDefault);

这也是行之有效的,如果空可能的对象不是一个变量:

It also works well if null-possible object isn't a variable:

string anybody = Parameters["Name"] 
              ?? Settings["Name"] 
              ?? GlobalSetting["Name"];

VS。

string anybody = (Parameters["Name"] != null ? Parameters["Name"] 
                 : (Settings["Name"] != null) ? Settings["Name"]
                 :  GlobalSetting["Name"];

这篇关于独特的方式使用空合并运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆