c# – 使用组播委托链接功能

我的问题在下面的代码中详细说明 – 我问的原因是我正在尝试代理:
//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返回….

所有的功能都会触发,因为各种消息“a被调用”等都被打印到控制台,但只返回从上一个函数e返回的数量 – 我假设在后台他们被返回,但是被覆盖?

解决方法

当您的问题中有一个多播代理(如d)时,返回值是d的调用列表的最后一个方法的返回值.

一般来说,对于多播代理,使用返回类型void是最自然的.

编译器没有机会猜到你希望10 2 3 4 5 6.你没有在任何地方指定它.

您可以将代理类型更改为:

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; }

然后,多播代理实例d将被调用

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

我希望这有帮助.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...