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

后端 未结 3 1435
太阳男子
太阳男子 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 02:06

    Well, this is ugly but...

    static bool NoNulls(params Func[] funcs) {
        for (int i = 0; i < funcs.Length; i++)
            if (funcs[i]() == null) return false;
    
        return true;
    }
    
    
    

    Then call it with:

    if (NoNulls(() => obj,
                () => obj.Parameters,
                () => obj.Parameters.UserSettings)) {
        // do something
    }
    

    Basically you're providing delegates to evaluate the values lazily, rather than the values themselves (as evaluating those values is what causes an exception).

    I'm not saying it's nice, but it's there as an option...

    EDIT: This actually (and accidentally) gets to the heart of what Dan was after, I think. All a method's arguments are evaluated before the method itself is executed. Using delegates effectively lets you delay that evaluation until the method needs to call the delegate to retrieve the value.

    提交回复
    热议问题