问题描述
我正在尝试理解代表的概念并提出了疑问。假设我们有一个委托,其返回类型定义为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参数并返回结果。
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;
}
现在,将添加和乘法方法添加到此委托中,然后委托的调用方式如下:
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
这篇关于调用具有多个具有返回值的函数的委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!