Func委托不链接方法 [英] Func delegate doesn't chain methods

查看:60
本文介绍了Func委托不链接方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们想象简单的委托调用:

Lets imagine simple delegate calls:

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,然后调用然后方法Sub。

So, why Add method was not called? I'm expecting to call Method Add, and then method Sub.

推荐答案

添加已正确链接并调用,请查看

Add was correctly chained and called, take a look at the result of

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方法的结果,因为无法访问它。如果返回链接,则返回值的代表返回被调用的最后一个方法的值,即被添加到代表的最后一个方法。

What is not chained, because there is no way to access it, is the result of the Add method. Delegates that return a value, in case of chaining, return the value of the last method invoked, that is the last method that was added to the delegate.

C#4.0语言规范


调用一个委托实例,该委托实例的调用列表包含
多个条目,是通过依次依次依次调用
调用列表中的每个方法来进行的。 ...
如果委托调用包含输出参数或
返回值,则它们的最终值将来自列表中最后一个委托
的调用。

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.

这篇关于Func委托不链接方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆