Shorthand for nested null checking C#

后端 未结 5 1677
伪装坚强ぢ
伪装坚强ぢ 2020-12-17 09:38

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

string src;
if((ParentContent!= null)
    &&am         


        
5条回答
  •  独厮守ぢ
    2020-12-17 09:54

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

    R NotNull(this T src, Func 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 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;
    

提交回复
热议问题