如何在 C# 中合并 Multicast Delegates 返回的结果?

How to combine the results returned by Multicast Delegates in C#?

我想通过调用多播委托合并两个函数调用返回的结果。但是我不断收到一个异常,说 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();
        }
    }
}

你能解释一下并帮助我修复错误吗?

您需要将调用列表中的每个函数都转换为委托类型才能使用正常的函数调用语法:

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);
}

还解决了这样一个问题,即您的委托调用不会有任何结果,因为它们 return void

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

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);