Getting all results from Func call

后端 未结 3 929
逝去的感伤
逝去的感伤 2021-01-24 17:34

The concept of delegates aren\'t too new to me but I cannot seem to find out how to get all results from a Func delegates. More specifically, I have a class that has a Func dele

3条回答
  •  有刺的猬
    2021-01-24 18:00

    You are using the wrong pattern. I'd recommend storing a list of these delegates and iterating over the list, rather than using multidelegates to call multiple targets.

    You can make this work (if you need to) by changing the signature to include a "state" variable that is passed by reference to each caller:

    private Action qualificationCheckCallback;
    
    public class QualCheckState { public bool Passed { get; set; } }
    
    // Call it thus:
    var state = new QualCheckState { Passed = true }; // Hope for the best
    qualificationCheckCallback(someEmployee, someShift, state);
    if (state.Passed) {
        // Assume everyone passed
    }
    

    Keep in mind, this requires the callees to honor the signature, and not overwrite anyone else's failed state:

    public void SomeCallee(Employee e, Shift s, State state) {
       // If some other check failed, don't bother doing our check.
       if (!state.Passed) return;
       // Do some check here
       if (checkFailed) state.Passed = false;
    }
    

    Of course, you can also extend this pattern to make it safer:

    public class QualCheckState {
        private List _results = new List();
        public bool Passed { get { return _results.All(s => s); }
        public void RecordResult(bool result) {
            _results.Add(result);
        }
    }
    

提交回复
热议问题