c# - 捕获委托(delegate)的所有返回值

标签 c# delegates

我在玩委托(delegate)和匿名方法时发现了下面的代码:

delegate int IntegerGenerator();
static void Main()
{
    IntegerGenerator numberGenerator;

    numberGenerator = () =>
    {
        Console.WriteLine("returns 7");
        return 7;
    };
    numberGenerator += () =>
    {
        Console.WriteLine("returns 3");
        return 3;
    };

    // This will always return 3
    var num = numberGenerator();

    Console.WriteLine("Return value: {0}", num);
}

我对委托(delegate)调用列表中所有方法的返回值很感兴趣。然而,似乎唯一返回的值来自附加到委托(delegate)的最后一个方法。 一种可能的解决方法是输入一个集合并将结果添加到其中。但是,由于委托(delegate)的返回类型,这似乎不是解决此问题的正确方法。

如何捕获委托(delegate)中附加方法的所有返回值?

最佳答案

您需要使用 MulticastDelegate.GetInvocationList并分别调用每个委托(delegate)。例如:

List<int> results = numberGenerator.GetInvocationList()
                                   .Cast<IntegerGenerator>()
                                   .Select(x => x())
                                   .ToList();

关于c# - 捕获委托(delegate)的所有返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19421702/

相关文章:

c# - 在 C# 中,为什么我不能测试事件处理程序在其定义的类之外的任何位置是否为 null?

f# - 将 C# 委托(delegate)转换为 f#

c# - 执行多播委托(delegate)

c# - Windows 与 VCE 上的 LDAP 绑定(bind)

c# - asp.net:response.redirect 上的 session 清除?

c# - 在 .NET 中使用 Thread.Abort() 和处理 ThreadAbortException 是否安全?

c# - 使用委托(delegate)或接口(interface)来分离日志记录 - 最佳实践 - C#

c# - 如何正确使用 IReadOnlyDictionary?

c# - 在 C# 中读取一个简单的 XML 配置文件

objective-c - NSTokenField 委托(delegate)