简体   繁体   中英

Get result from Delegate Invocation list

I have very simple question. I have very little understanding of Delegates and Lambda Expressions in C# . I have code:

class Program
{
    delegate int del(int i);
    static void Main(string[] args)
    {
        del myDelegate = Multiply;
        int j;

        myDelegate = x => { Console.WriteLine("Lambda Expression Called..."); return x * x; };            
        myDelegate += Multiply;
        myDelegate += Increment;

        j = myDelegate(6);

        Console.WriteLine(j);
        Console.ReadKey();
    }

    public static int Multiply(int num)
    {
        Console.WriteLine("Multiply Called...");
        return num * num;
    }
    public static int Increment(int num) 
    {
        Console.WriteLine("Increment Called...");
        return num += 1;
    }
}

And the result is:

Lambda Expression Called...
Multiply Called...
Increment Called...
7

It shows the result 7 of the last method called from invocation list.

How can I get the result of each method from Delegate Invocation List? I have seen this thread but I couldn't grasp the idea. I will appreciate if you can provide answer with my code provided above.

Thank You!

It's fairly unusual to use the multicast capability of .NET delegates for anything other than event-subscribers (consider simply using a collection instead).

That said, it's possible to get the individual delegates comprising a multicast delegate (with Delegate.GetInvocationList ) and invoke each of them in turn instead of getting the framework to do it for you (by invoking the multicast delegate directly). This way, it's possible to inspect the return-value of each member of the invocation list.

foreach(del unicastDelegate in myDelegate.GetInvocationList())
{
    int j = unicastDelegate(6);
    Console.WriteLine(j);
}

Output:

Lambda Expression Called...
36
Multiply Called...
36
Increment Called...
7

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM