我的问题在以下代码中有详细说明 - 我问这个的原因是我正在试验委托(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....
所有函数都会触发,因为各种消息“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/