Func类型的多播委托(具有返回值)? [英] Multicast delegate of type Func (with return value)?

查看:279
本文介绍了Func类型的多播委托(具有返回值)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

Func<string, string> func1 = (param) =>
{
    Console.WriteLine("Func 1 executing");
    return "Hello" + param;
};
Func<string, string> func2 = (param) =>
{
    Console.WriteLine("Func 2 executing");
    return "World" + param;
};
Func<string, string> funcSum = func1 + func2;
string funcResult = funcSum("!");
Console.WriteLine(funcResult);

输出为:

Func 1 executing
Func 2 executing
World!

求和:

Func<string, string> funcSum = func2 + func1;

给出输出:

Func 2 executing
Func 1 executing
Hello!

我的初始测试是使用布尔返回类型完成的,返回值也始终由最后一个功能。它按预期工作吗?我们会失去其他函数的返回值吗?如果是这样,那么在现实世界中是否存在这些功能的多播委托的用例?

My initial test was done with a boolean return type, and the returned value was also always determined by the last function. Is it working as intended ? Aren't we losing the return value of the other functions ? If so, is there a use case in real world of those multicast delegate of functions ?

推荐答案


Is it working as intended?

至少按规定工作。无论您想要的是什么,这都是不同的事情:)与C#5规范的15.4节-强调我的想法一样:

It's working as specified, at least. Whether that's what you intended or not is a different matter :) From section 15.4 of the C# 5 specification - emphasis mine:


通过依次同步调用调用列表中的每个方法,可以继续执行其调用列表包含多个条目的委托实例。所谓的每个方法都传递给委托实例相同的参数集。如果这样的委托调用包含引用参数(第10.0.6.1.2节),则每个方法调用都将引用相同的变量;否则,每个方法调用都将引用同一变量。通过调用列表中的一种方法对该变量所做的更改将对调用列表下方的方法可见。 如果委托调用包含输出参数或返回值,则它们的最终值将来自列表中最后一个委托的调用。

下一步:


我们是否失去其他函数的返回值?

Aren't we losing the return value of the other functions ?

此刻是。


如果是,是在现实世界中,有一个使用这些函数的多播委托的用例吗?

If so, is there a use case in real world of those multicast delegate of functions ?

说实话,这很少。但是,您可以使用 Delegate.GetInvocationList()

Very rarely, to be honest. However, you can split a multicast delegate apart, using Delegate.GetInvocationList():

foreach (Func<string, string> func in funcSum.GetInvocationList())
{
    Console.WriteLine(func("!"));
}

这篇关于Func类型的多播委托(具有返回值)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆