使用具有返回值的多个函数调用委托 [英] Calling delegate with multiple functions having return values

查看:24
本文介绍了使用具有返回值的多个函数调用委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解代表的概念并且有一个疑问.假设我们定义了一个委托,其返回类型为 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

这篇关于使用具有返回值的多个函数调用委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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