c# - 如何访问以前添加到委托(delegate)的函数

标签 c# delegates func

<分区>

我是委托(delegate)新手,据我所知,您可以向委托(delegate)添加两个或更多函数(使用 +=)。但是当你激活一个委托(delegate)时,它总是会调用最后添加的函数。如果我想调用之前添加的函数怎么办?假设我有:

public static int add(int o1, int o2)
{
   return o1 + o2;
}

public static int multiply(int o1, int o2)
{
    return o1 * o2;
}

public static int minus(int o1, int o2)
{
    return o1 - o2;
}

所以我使用一个委托(delegate)(实际上是一个 Func)来添加所有这些函数。

Func<int, int, int> f;
f = add;
f += multiply;
f += minus;

现在假设我想调用multiplyadd,我不能这样做,如果我使用:

Console.WriteLine(f(1,2));

它只会调用minus

编辑

顺便说一句,我知道可以使用-= 来删除函数,但是如果有大量函数,就不方便了。我正在寻找的解决方案是索引(如数组)

f[2](5,3) 

好像不行。

最佳答案

这在 language specification 中有明确规定(强调我的):

Invocation of a delegate instance whose invocation list contains multiple entries proceeds by invoking each of the methods in the invocation list, synchronously, in order. [...] If the delegate invocation includes output parameters or a return value, their final value will come from the invocation of the last delegate in the list.

所以并不是说其他​​委托(delegate)没有被执行。他们是。只是只返回最后一个委托(delegate)的返回值。如果其他委托(delegate)有一些副作用,比如打印到控制台,您就会看到它们。

编辑

如果你想像这样访问委托(delegate):

f[2](5,3) 

那么你可能需要一个List<Func<int, int, int>>而不是多播委托(delegate)。

关于c# - 如何访问以前添加到委托(delegate)的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57669978/

相关文章:

c# - MVVM 架构 WPF

c# - 向下转型为泛型

ios - 在 swift4 中的 ViewController 之间传递数据

swift - 位置管理器在 gmsMapView swift 4.2 中显示错误位置

c# - 我可以设置一个带有运行时变量的 Func<> 函数来忽略将它们作为 C# 中的参数传递吗?

c# - 为什么成员字段不能有字段初始值设定项调用成员函数?

c# - 如何在 C# 中为 COM STA 线程发送消息?

ios - 没有segue的两个 View Controller 之间的快速委托(delegate)

arrays - 数组和 slice 数据类型

c# - 实体同时具有一对一和一对多两种关系