让我们想象一下简单的委托(delegate)调用:
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
那么,为什么Add方法没有被调用呢?我希望先调用方法 Add,然后然后调用方法 Sub。
最佳答案
Add 已正确链接并调用,查看结果
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)
{
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 方法的结果,因为无法访问它。返回值的委托(delegate),在链接的情况下,返回最后调用的方法的值,即添加到委托(delegate)的最后一个方法。
这在 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.
关于c# - Func 委托(delegate)不链接方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14463400/