c# - 为什么程序使用添加到委托(delegate)的最后一个方法?

标签 c# delegates

在 button1_click 上,一个消息框接一个出现 - 第一个显示 30,第二个显示 200:

public partial class Form1 : Form
{

    delegate void myMathFunction(int j, int q);

    void add(int x, int y) {MessageBox.Show((x + y).ToString());}

    void multiply(int x, int y){MessageBox.Show((x*y).ToString());}

    private void button1_Click(object sender, EventArgs e)
    {
        myMathFunction foo = new myMathFunction(add);
        foo+= new myMathFunction(multiply);

        foo.Invoke(10, 20);
    }

    public Form1() { InitializeComponent(); }
}

但下面直接进入 200,但我已将这两种方法都分配给委托(delegate) - 添加了什么,为什么选择使用乘法?

public partial class Form1 : Form
{

    delegate int myMathFunction(int j, int q);

    int add(int x, int y){return x + y;}

    int multiply(int x, int y) {return x * y;}

    private void button1_Click(object sender, EventArgs e)
    {
        myMathFunction foo = new myMathFunction(add);
        foo += new myMathFunction(multiply);

        MessageBox.Show(foo.Invoke(10, 20).ToString());
    }

    public Form1() { InitializeComponent(); }
}

是否可以修改第二个代码示例,以便委托(delegate)运行 add 方法而不是 multiply 方法?

最佳答案

当您的委托(delegate)有多个函数附加到它时,每个函数都会被依次调用。如果委托(delegate)有一个非空的返回值,最后一个函数的返回值就是返回的值。

language specification , 15.4 委托(delegate)调用,说

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.

因此,当您调用 foo.Invoke(10, 20) 时,会发生以下情况:

  • 首先,调用 add(10, 20) 并返回 30。
  • 然后,调用 multiply(10, 20) 返回 200 并将该值返回给原始调用者。

在你问的后续问题中

Can the second code sample be amended so that the delegate runs the add method rather than the multiply method?

如上所述,add 方法 multiply 方法都被执行。 上次执行 方法的返回值就是返回给调用者的值。因此,如果您希望返回调用 add 的结果,它必须是添加到委托(delegate)实例的最后一个方法。

关于c# - 为什么程序使用添加到委托(delegate)的最后一个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10567499/

相关文章:

c# - 我希望能够使用 lambda 表达式来指定要通过 wcf 服务返回的值范围

ios - UIWebview : How to notify UIViewController if any of the already loaded link in the web view fails to open

c# - 对委托(delegate)声明事件的 XML 注释

ios - 如何将自定义委托(delegate)设置为 UITableViewController?

c# - 如果操作几乎总是很快完成,是否应该使用异步?

c# - 从列表中删除不在*所有*位置的项目

c# - WP 运行时组件 - 类型加载异常?

c# - 无法在泛型委托(delegate)中推断出类型

c# - "SmtpFailedRecipientException: Mailbox unavailable"邮箱可用时

c# - 将方法从 View 移动到 View 模型 - WPF MVVM