让我们想象简单的委托电话:
void Main() { Func<int,int,string> tfunc = null; tfunc += Add; // bind first method tfunc += Sub; // bind second method Console.WriteLine(tfunc(2,2)); } private string Add(int a,int b) { return "Add: " + (a + b).ToString(); } private string Sub(int a,int b) { return "Sub: " + (a - b).ToString(); }
这个程序的结果是:
Sub: 0
解决方法
添加被正确链接和调用,看看结果
void Main() { Func<int,int b) { Console.WriteLine("Inside Add"); return "Add: " + (a + b).ToString(); } private string Sub(int a,int b) { Console.WriteLine("Inside Sub"); return "Sub: " + (a - b).ToString(); }
它是:
Inside Add Inside Sub Sub: 0
什么不链接,因为没有办法访问它,是Add方法的结果.在链接的情况下返回值的代表返回调用的最后一个方法的值,即添加到委托中的最后一个方法.
这在C# 4.0 language specification的第15.4部分中有所规定
Invocation of a delegate instance whose invocation list contains multiple entries proceeds by invoking each of the methods in the invocation list,synchronously,in order. … If the delegate invocation includes output parameters or a return value,their final value will come from the invocation of the last delegate in the list.