Getting all results from Func call

后端 未结 3 931
逝去的感伤
逝去的感伤 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 17:57

    As mentioned in Andrew's answer, if you simply invoke qualificationCheckCallback like a normal method, you'll only get back the return value from one of the methods. For this reason, it's pretty unusual to have multicast delegates that have a return value.

    If your goal is to see if at least one of the methods stored in your delegate returns false, you'll need to invoke the methods individually. Here is one way to do that using the Delegate.GetInvocationList() method:

    bool hasAtLeastOneFalse = false;
    if (qualificationCheckCallback != null)
    {
        foreach(var f in qualificationCheckCallback.GetInvocationList()
                                                   .Cast>())
        {
            if (!f(employee, shift))
            {
                hasAtLeastOneFalse = true;
                // break; // If you don't care about invoking all delegates, you can choose to break here.
            }
        }
    }
    
    Console.WriteLine(hasAtLeastOneFalse);
    

    I'm not suggesting this is a good practice, but it can be done.

提交回复
热议问题