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

标签 c# delegates

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

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

最佳答案

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

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

还修复了这样一个事实,即您的委托(delegate)调用在返回 void 时不会有任何结果。

关于c# - 如何在 C# 中合并 Multicast Delegates 返回的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31636702/

相关文章:

c# - 只读文本框的服务器验证 - 防止输入值

c# - 移除多次出现的数组元素

c# - 使用 new() 或 default 初始化变量之间的区别?

design-patterns - Groovy 中@Delegate、@Mixin 和 Traits 的区别?

c++ - 如何创建一个 function_list<> 类来保存具有相同模板语法的 std::function<> vector ?

c# - 在 DbContext 中看不到 Entity Framework 数据库更改

c# - 如何在新线程中调用长方法以保持 UI 在 C# 中运行

objective-c - 我应该将通过 Interface Builder 进行的委托(delegate)引用设为 nil 吗?

c# - 在运行时将 lambda 转换为委托(delegate)

c# - 实例化要在类库中使用的委托(delegate)方法