使用多播代理链接功能

时间:2013-03-05 15:37:30

标签: c# delegates

我的问题在下面的代码中有详细说明 - 我之所以这样说是因为我正在试验代表:

//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被调用”等都被打印到console,但只返回从最后一个函数e返回的数量 - 我假设在他们返回的背景却被覆盖了吗?

2 个答案:

答案 0 :(得分:14)

如果您的问题中有d这样的多播代理,则返回值是{调用列表{的 last 方法的返回值{1}}。

通常,对于多播委托,最常使用返回类型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

我希望这会有所帮助。

答案 1 :(得分:9)

这不是代表处理返回类型的方式。会发生什么是所有的处理程序将彼此独立地执行,然后将随机选择一个(技术上它是最后订阅的处理程序,但你不应该依赖它)返回给调用者调用了委托。

我强烈反对您不要使用具有返回值的事件(您将此委托当作事件处理)。这种行为几乎不可取。如果你想要一个返回值,那么确保你的委托总是映射到一个函数是合理的,不多也不少。

至于实际产生所需的结果,虽然有很多方法,但你会更好地使用更传统的代表集合:

List<Func<int, int>> functions = new List<Func<int, int>>();
//populate

int result = functions.Aggregate(10, (total, func) => func(total));
相关问题