Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all returned strings form methods in delegate

Tags:

c#

delegates

I have a question about delegate in this code, I add three method to delegate. There're return a string. In the line

string delOut = del("Beer");

to my valuable delOut delegate assignet this "Length : 4"

How can I collect all strings that methods in delegate returns ?

public class NaForum
{
    public delegate string MyDelegate(string s);

    public void TestDel()
    {
        MyDelegate del = s => s.ToLower();
        del += s => s.ToUpper();
        del += s => string.Format("Length : {0}", s.Length);

        string delOut = del("Beer");
        Console.WriteLine(delOut);
    }
}

Thanks for any answers.

like image 968
Zabaa Avatar asked Dec 27 '22 01:12

Zabaa


2 Answers

You need to use Delegate.GetInvocationList:

var results = new List<string>();

foreach (MyDelegate f in del.GetInvocationList()) {
    results.Add(f("Beer"));
}

Now, results holds all of the return values.

like image 89
jason Avatar answered Dec 28 '22 16:12

jason


See C#:Creating Multicast delegate with boolean return type: You need to do the multicasting by yourself to get the individual return values.

like image 25
Medinoc Avatar answered Dec 28 '22 14:12

Medinoc