Calling delegate with multiple functions having return values(使用具有返回值的多个函数调用委托)
问题描述
我正在尝试理解代表的概念并且有一个疑问.假设我们定义了一个委托,其返回类型为 int,并接受 2 个 int 类型的参数.
I am trying to understand concept of delegates and have got a query. Suppose that we have a delegate defined with return type as int and accepting in 2 parameters of type int.
委托声明:
public delegate int BinaryOp(int x, int y);
现在,假设我们有 2 个方法(加法和乘法),它们都接受 2 个 int 参数并返回一个 int 结果.
Now, lets say we have 2 methods (add and multiply) both accepting 2 int parameters and returning an int result.
代码:
static int Add(int x, int y)
{
return x + y;
}
static int Multiply(int x, int y)
{
return x * y;
}
现在,当 add 和 multiply 方法被添加到这个委托中,然后当委托被调用时:
Now, when add and multiply methods are added into this delegate, and then when the delegate is called like:
BinaryOp b = new BinaryOp(Add);
b+=new BinaryOp(Multiply);
int value=delegate_name(2,3);
然后,根据我的理解,这两种方法都被调用了.现在,这两种方法中的哪一种的结果存储在 value 变量中?还是在这种情况下返回一个数组?
Then, as per my understanding, both the methods are called. Now, result from which of the 2 methods is stored in the value variable? Or does it return an array in such case?
推荐答案
其实一点点诡计和强制转换,就可以得到如下所有结果:
Actually, with a little bit of trickery and casting, you can get all of the results like this:
var b = new BinaryOp(Add);
b += new BinaryOp(Multiply);
var results = b.GetInvocationList().Select(x => (int)x.DynamicInvoke(2, 3));
foreach (var result in results)
Console.WriteLine(result);
有输出:
5
6
这篇关于使用具有返回值的多个函数调用委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用具有返回值的多个函数调用委托


- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 输入按键事件处理程序 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01