使用具有返回值的多个函数调用委托

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)