gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:32:32 24 4
gpt4 key购买 nike

我想通过调用多播委托(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com