是否有一个"相反"对空合并运算符? (......在任何语言?) [英] Is there an "opposite" to the null coalescing operator? (…in any language?)

查看:83
本文介绍了是否有一个"相反"对空合并运算符? (......在任何语言?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

空合并大致翻译返回X,除非是null,在这种情况下,回报是

我经常需要返回null如果x为空,否则返回xy格式的

我可以使用返回X == NULL?空:xy格式的;

不坏,但中间始终困扰着我 - 这似乎是多余的。我想preFER像返回X :: XY; ,哪里有什么遵循评估只有当什么precedes它不是

Not bad, but that null in the middle always bothers me -- it seems superfluous. I'd prefer something like return x :: x.y;, where what follows the :: is evaluated only if what precedes it is not null.

我认为这是的几乎的相反为空聚结,有种混在一个简洁,内联零检查,但我[几乎的]确定有在C#中没有这样的运营商。

I see this as almost an opposite to null coalescence, kind of mixed in with a terse, inline null-check, but I'm [almost] certain that there is no such operator in C#.

(我知道我可以在C#编写的方法吧,我用返回NullOrValue.of(X,()=> XY); ,但如果你有什么更好的,我想看到​​这一点。)

(I know that I can write a method for it in C#; I use return NullOrValue.of(x, () => x.y);, but if you have anything better, I'd like to see that too.)

推荐答案

有年代的空安全的对其操作的(?)在Groovy ...我想这就是你以后。

There's the null-safe dereferencing operator (?.) in Groovy... I think that's what you're after.

(它也被称为安全航行运营商

例如:

homePostcode = person?.homeAddress?.postcode

这将给空,如果 person.homeAddress person.homeAddress。后code 为null。

This will give null if person, person.homeAddress or person.homeAddress.postcode is null.

(这是现在在C#6.0 可用,但不是在早期版本)

(This is now available in C# 6.0 but not in earlier versions)

这篇关于是否有一个"相反"对空合并运算符? (......在任何语言?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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