【发布时间】:2013-02-20 02:16:15
【问题描述】:
我的问题在下面的代码中有详细说明 - 我问这个的原因是我正在试验代表:
//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 被调用”等各种消息都会打印到console,但只返回从最后一个函数e 返回的数量 - 我假设它们在后台是被返回但随后被覆盖?
【问题讨论】:
-
为了获得这种递归,我认为您必须将前一个委托作为参数传递。否则,您只需添加 10 + 6 = 16。
-
@DavinTryon 这不是真正的递归。没有任何函数调用自己;它只是函数的链接。
-
@Servy 是的,更像“嵌套”函数?是否有一个功能语言名称?
-
@DavinTryon ...这正是正在发生的事情 - 它返回 16
-
另一个问题是异常。如果其中一种方法抛出异常,您将不会以编程方式知道它是哪一种,也不会知道哪些方法未执行。