C#如果空,则空EX pression [英] C# if-null-then-null expression
问题描述
只是出于好奇/便利:C#提供了两个爽条件前pression功能我知道的:
Just for curiosity/convenience: C# provides two cool conditional expression features I know of:
string trimmed = (input == null) ? null : input.Trim();
和
string trimmed = (input ?? "").Trim();
我错过这样的EX pression的情况下,我面临着非常频繁:
I miss another such expression for a situation I face very often:
如果输入参考为空,则输出为空。否则,输出应该是访问输入对象的方法或属性的结果。强>
我所做的正是,在我的第一个例子,但(输入== NULL)?空:input.Trim()
相当冗长且无法读取
I have done exactly that in my first example, but (input == null) ? null : input.Trim()
is quite verbose and unreadable.
有另一种条件EX pression这种情况下,还是可以使用 ??
操作符优雅?
Is there another conditional expression for this case, or can I use the ??
operator elegantly?
推荐答案
喜欢的东西Groovy的空安全的对其操作?
Something like Groovy's null-safe dereferencing operator?
string zipCode = customer?.Address?.ZipCode;
据我了解,在C#团队已经看了这一点,并发现它不是那么简单,设计优雅正如人们所预料......虽然我没有听说过的问题的细节。
I gather that the C# team has looked at this and found that it's not as simple to design elegantly as one might expect... although I haven't heard about the details of the problems.
我不相信有任何这样的事情,在语言的那一刻,我怕......我还没有听说过什么打算呢,虽然这并不是说就不会发生在一些点。
I don't believe there's any such thing in the language at the moment, I'm afraid... and I haven't heard of any plans for it, although that's not to say it won't happen at some point.
编辑:它现在将会是C#6部分,为空条件运算符
It's now going to be part of C# 6, as the "null-conditional operator".
这篇关于C#如果空,则空EX pression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!