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
这篇关于使用具有返回值的多个函数调用委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用具有返回值的多个函数调用委托
基础教程推荐
- rabbitmq 的 REST API 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01