Can I force my own short-circuiting in a method call?

后端 未结 3 1438
太阳男子
太阳男子 2021-02-10 01:37

Suppose I want to check a bunch of objects to make sure none is null:

if (obj != null &&
    obj.Parameters != null &&
    obj.Parameters.UserSet         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-10 01:47

    You could write a function that accepts an expression tree and transforms that tree into a form that will check for nulls, and return a Func that could be safely evaluated to determine if there is a null.

    I suspect that while the resulting code may be cool, it would be confusing, and much less performant than just writing a bunch of short-circuited a != null && a.b != null... checks. In fact, it would likely be less performant than just checking all the values and catching the NullReferenceException (not that I advocate for exception handling as a flow of control mechanism).

    The signature for such a function would be something like:

    public static Func NoNulls( Expression> expr )
    

    and it's usage would look something like:

    NoNulls( () => new { a = obj, 
                         b = obj.Parameters, 
                         c = obj.Parameters.UserSettings } )();
    

    If I get some free time, I will write a function that does just such an expression tree transformation and update my post. However, I'm sure that Jon Skeet or Mark Gravell could write such a function with one eye closed and one hand behind their back.

    I would also love to see C# implement the .? operator that Eric alludes to. As a different Eric (Cartman) might say, that would "kick ass".

提交回复
热议问题