在 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/