使用空合并运算符的独特方法

Unique ways to use the null coalescing operator(使用空合并运算符的独特方法)
本文介绍了使用空合并运算符的独特方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我知道在 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"];

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

ActiveDirectory error 0x8000500c when traversing properties(遍历属性时 ActiveDirectory 错误 0x8000500c)
search by samaccountname with wildcards(使用通配符按 samaccountname 搜索)
Get the list of Groups for the given UserPrincipal(获取给定 UserPrincipal 的组列表)
Can you find an Active Directory User#39;s Primary Group in C#?(你能在 C# 中找到 Active Directory 用户的主要组吗?)
Query From LDAP for User Groups(从 LDAP 查询用户组)
How can I get DOMAINUSER from an AD DirectoryEntry?(如何从 AD DirectoryEntry 获取 DOMAINUSER?)