速记嵌套空检查C#

问题描述:

据我所知没有一个显著更优雅编写如下....

As far as I know there is not a significantly more elegant way to write the following....

string src;
if((ParentContent!= null)
    &&(ParentContent.Image("thumbnail") != null)
    &&(ParentContent.Image("thumbnail").Property("src") != null))
    src = ParentContent.Image("thumbnail").Property("src").Value

你觉得应该有一个C#语言的功能,使这个短?结果
如果是这样,我应该看起来像结果
为例,像延长???运营商

Do you think there should be a C# language feature to make this shorter?
And if so, what should it look like?
for example, something like extending the ?? operator

string src = ParentContent??.Image("thumbnail")??.Property("src")??.Value;



道歉为虚构的例子,我的过分简化的解决方案。

Apologies for the rather contrived example, and my over-simplified solution.

修改......许多年后结果
现在这是有计划的语言功能称为空传播运营商
的https://罗斯林。 codeplex.com/discussions/540883 (感谢@布赖恩)

Edit ... Many years later
This is now a planned language feature called the "Null propagating operator" ?. https://roslyn.codeplex.com/discussions/540883 ( Thanks @Brian )

有没有内置的语法做这一点,但你可以定义一个扩展的方法来做到这一点:

There is no built-in syntax for doing this, but you can define an extension method to do this:

R NotNull<T, R>(this T src, Func<T, R> f) 
    where T : class where R : class {
  return src != null ? f(src) : null;
}

现在,你可以重写你的例子如下:

Now, you can rewrite your example as follows:

src = ParentContent.NotNull(p => p.Image("thumbnail")).
        NotNull(i => i.Property("src")).NotNull(src => src.Value);



这是不是很好,因为它可能是一个语法的支持,但我会说这是多少更具可读性。

It is not as nice as it may be with a syntactic support, but I'd say it's much more readable.

请注意,这增加了 NOTNULL 方法把所有的.NET类型,这可能是有点不方便。你可以解决通过定义一个简单的包装类型 WrapNull&LT; T&GT;其中T:类仅包含类型的值 T 键,用于打开任何引用类型为 WrapNull $的方法C $ C>,并在 WrapNull 键入提供 NOTNULL 。然后代码是这样的:

Note that this adds the NotNull method to all .NET types, which may be a bit inconvenient. You could solve that by defining a simple wrapper type WrapNull<T> where T : class containing only a value of type T and a method for turning any reference type into WrapNull and providing the NotNull in the WrapNull type. Then the code would look like this:

src = WrapNull.Wrap(ParentContent).NotNull(p => p.Image("thumbnail")).
        NotNull(i => i.Property("src")).NotNull(src => src.Value);



(这样你就不会污染每一种类型的新扩展方法的智能感知)

(So you wouldn't pollute the IntelliSense of every type with the new extension method)

通过更努力一点,你也可以定义一个LINQ查询运营商这样做。这是一个有点矫枉过正,但它有可能写这个(我将不包括这里的定义,因为它们的时间长一点,但它是可能的情况下,有人有兴趣: - )。)

With a bit more effort, you could also define a LINQ query operators for doing this. This is a bit overkill, but it is possible to write this (I won't include the definitions here as they are a bit longer, but it's possible in case someone is interested :-)).

src = from p in WrapNull.Wrap(ParentContent)
      from i in p.Image("thumbnail").
      from src in i.Property("src")
      select src.Value;