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.
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)
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;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…