Multicast delegate of type Func (with return value)?

Multicast delegate of type Func (with return value)?

Is it working as intended?

It's working as specified, at least. Whether that's what you intended or not is a different matter :) From section 15.4 of the C# 5 specification - emphasis mine:

Invocation of a delegate instance whose invocation list contains multiple entries proceeds by invoking each of the methods in the invocation list, synchronously, in order. Each method so called is passed the same set of arguments as was given to the delegate instance. If such a delegate invocation includes reference parameters (§10.6.1.2), each method invocation will occur with a reference to the same variable; changes to that variable by one method in the invocation list will be visible to methods further down the invocation list. If the delegate invocation includes output parameters or a return value, their final value will come from the invocation of the last delegate in the list.

Next:

Aren't we losing the return value of the other functions ?

Yes, at the moment.

If so, is there a use case in real world of those multicast delegate of functions ?

Very rarely, to be honest. However, you can split a multicast delegate apart, using Delegate.GetInvocationList():

foreach (Func<string, string> func in funcSum.GetInvocationList())
{
    Console.WriteLine(func("!"));
}

Calling delegate with multiple functions having return values

I am trying to understand concept of delegates and have got a query. Suppose that we have a delegate defined with return type as int and accepting in 2 parameters of type int.

Delegate declaration:

 public delegate int BinaryOp(int x, int y); 

Now, lets say we have 2 methods (add and multiply) both accepting 2 int parameters and returning an int result.

Code:

    static int Add(int x, int y)  
   {     
        return x + y; 
    }  

    static int Multiply(int x, int y)  
   {     
        return x * y; 
    }  

Now, when add and multiply methods are added into this delegate, and then when the delegate is called like:

BinaryOp b = new BinaryOp(Add);
b+=new BinaryOp(Multiply);

int value=delegate_name(2,3);

Then, as per my understanding, both the methods are called. Now, result from which of the 2 methods is stored in the value variable? Or does it return an array in such case?

回答1

Actually, with a little bit of trickery and casting, you can get all of the results like this:

var b = new BinaryOp(Add);
b += new BinaryOp(Multiply);

var results = b.GetInvocationList().Select(x => (int)x.DynamicInvoke(2, 3));
foreach (var result in results)
    Console.WriteLine(result);

With output:

5
6

回答2

You will get the return value of the last method added to the multicast delegate. In this case, you will get the return value of Multiply.

See the documentation for more on this: https://msdn.microsoft.com/en-us/library/ms173172.aspx

原文地址:https://www.cnblogs.com/chucklu/p/14389887.html