c# - 使用多播委托(delegate)链接函数

标签 c# delegates

我的问题在以下代码中有详细说明 - 我问这个的原因是我正在试验委托(delegate)​​:

//create the delegate          
delegate int del(int x);

class Program {


    static void Main(string[] args) {

        Program p;
        p = new Program();

        del d = p.a;
        d += p.b;
        d += p.c;
        d += p.d;
        d += p.e;
        Console.WriteLine(d(10)); //<<was hoping it would be 10+2+3+4+5+6

        Console.WriteLine("press [enter] to exit");
        Console.ReadLine();
    }

    private int a(int x) { Console.WriteLine("a is called"); return x + 2; }
    private int b(int x) { Console.WriteLine("b is called"); return x + 3; }
    private int c(int x) { Console.WriteLine("c is called"); return x + 4; }
    private int d(int x) { Console.WriteLine("d is called"); return x + 5; }
    private int e(int x) { Console.WriteLine("e is called"); return x + 6; }

} 

返回 16....

enter image description here

所有函数都会触发,因为各种消息“a is called”等都打印到 console 但只返回从最后一个函数 e 返回的金额- 我在后台假设它们被返回但随后被覆盖?

最佳答案

当您的问题中有一个像 d 这样的多播委托(delegate)时,返回值是调用的 last 方法的返回值d 的列表。

一般来说,对于多播委托(delegate),最自然的做法是使用返回类型void

编译器没有机会猜测您希望得到 10+2+3+4+5+6。您没有在任何地方指定它。

您可以将委托(delegate)类型更改为:

delegate void del(int xToAdd, ref int sum);

例如,您的方法 a 应该如下所示:

private void a(int x, ref int sum) { Console.WriteLine("a is called"); sum += x + 2; }

多播委托(delegate)实例 d 然后会像这样调用:

int sum = 0;
d(10, ref sum);
Console.WriteLine(sum);

希望对您有所帮助。

关于c# - 使用多播委托(delegate)链接函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15227876/

相关文章:

c# - 如何查找我的 Azure 构建代理的 C# 版本

c++ - QListView 样式表不适用于委托(delegate)

c# - 将一种类型的委托(delegate)动态转换为另一种

c# - 如何跨类发布和订阅事件

c# - 使用文件流从根目录文件夹读取文件

c# - nhibernate 审计更新事件

c# - 静态构造函数性能以及为什么我们不能指定 beforefieldinit

ios - 使用 iOS 委托(delegate)

c# - 在子类中使用事件和委托(delegate)

c# - 类数组