Best syntax for a = (x == null) ? null : x.func()

后端 未结 7 825
囚心锁ツ
囚心锁ツ 2020-12-24 04:50

Basic question here - I have many lines of code that look something like:

var a = (long_expression == null) ? null : long_expression.Method();
7条回答
  •  佛祖请我去吃肉
    2020-12-24 05:33

    You can write an extension method for whatever type long_expression evaluates to:

    public static object DoMethod(this MyType pLongExpression)
    {
       return pLongExpression == null ? null : pLongExpression.Method();
    }
    

    This will be callable on any MyType reference, even if that reference is null.

提交回复
热议问题