c# - Func 委托(delegate)不链接方法

标签 c# delegates func

让我们想象一下简单的委托(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/

相关文章:

c# - 比较.net中的日期

c# - 将一个事件处理程序添加到另一个事件处理程序

c# - 在 LINQ 中使用命名元组数组

c# - Web 浏览器键盘快捷键

ios - Swift 委托(delegate)作为函数参数

c# - 从 IQueryable<T> 谓词获取 Func<T, bool>

swift 3 : func as argument

python - 使用“函数”中的 "for loop"打印数据帧每列的最小值/最大值

c# - 如何在 Powershell 中为实现 IDictionary 和 ICollection 的类的实例设置属性

c# - 将委托(delegate)传递给一个非托管方法,该方法需要一个带有 int 数组指针的委托(delegate)方法