如何在C#中组合多播代理返回的结果?

时间:2015-07-26 11:57:53

标签: c# delegates

我想通过调用多播委托来组合两个函数调用返回的结果。但我一直得到一个例外,说del是一个变量但是像方法一样使用。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MultiDelegateConsoleApplication
{
    public delegate void SampleMultiDelegate(string args,out string SampleString);

    class Program
    {
        public static void SayHello(string args,out string s1)
        {
            s1 = "Hello " + args;
        }
        public static void SayGoodbye(string args,out string s2)
        {
            s2 = "Goodbye " + args;
        }

        static void Main(string[] args)
        {
            SampleMultiDelegate sampleMultiDelegate = new SampleMultiDelegate(SayHello);
            sampleMultiDelegate += SayGoodbye;
            string param1 = "Chiranjib";
            string param2,param3;
            Console.WriteLine("**************Individual Function Invoke***********");
            SayHello(param1,out param2);
            SayGoodbye(param1, out param3);
            Console.WriteLine("**************Multicast Delegate Invoke***********");
            sampleMultiDelegate(param1,out param2);
            Console.WriteLine(param2); //The multicast delegate will always return the result of the last function
            string result;
            foreach (Delegate del in sampleMultiDelegate.GetInvocationList())
            {
                result = del(param1,out param2);
            }

            Console.ReadKey();
            Console.ReadLine();
        }
    }
}

请您解释并帮我解决错误?

2 个答案:

答案 0 :(得分:2)

您需要将调用列表中的每个函数强制转换为委托类型,以便能够使用普通函数调用语法:

void Main()
{
    var sampleMultiDelegate = new SampleMultiDelegate(SayHello);
    sampleMultiDelegate += SayGoodbye;
    var param1 = "Chiranjib";
    string param2;
    string result = "";
    foreach (var del in sampleMultiDelegate.GetInvocationList())
    {
        var f = (SampleMultiDelegate)del;
        f(param1, out param2);
        result += param2 + "\r\n";
    }

    Console.WriteLine(result);
}

还修复了以下事实:当您的委托调用返回void时,无法获得任何结果。

答案 1 :(得分:1)

此代码可用于获取每个结果。关键是我的unfurl函数,它改变了返回类型。

SampleMultiDelegate sampleMultiDelegate = new SampleMultiDelegate(SayHello);
sampleMultiDelegate += SayGoodbye;

string param1 = "Chiranjib";

Func<SampleMultiDelegate, string, string> unfurl =
    (d, p1) =>
    {
        string r;
        d(p1, out r);
        return r;
    };

string result =
    String.Join(
        Environment.NewLine,
        sampleMultiDelegate
            .GetInvocationList()
            .Cast<SampleMultiDelegate>()
            .Select(d => unfurl(d, param1)));

Console.WriteLine(result);