简体   繁体   English

在另一个事件处理程序中调用事件处理程

[英]calling a event handler within another event handler?

Here is the short sample code: 以下是简短的示例代码:

private void txtbox1_DoubleClick(object sender, EventArgs e)
{
    button1_Click(object sender, EventArgs e); //can I call button1 event handler?
}

private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show(txtbox1.Text);
}

I wonder if it would be okay to code in the above way? 我想知道以上述方式编码是否可行?

You can do that - although the code you provide can't be compiled. 你可以这样做 - 虽然你提供的代码无法编译。 It should look like this: 它应该如下所示:

private void txtbox1_DoubleClick(object sender, EventArgs e)
{
    button1_Click(sender, e);
}

private void button1_Click(object sender, EventArgs e)
{
    MessageBox.Show(txtbox1.Text);
}

But for best practice and code readability, you're probably better off doing this, especially as you are not making use of sender and e : 但是为了获得最佳实践和代码可读性,你可能最好不要这样做,特别是因为你没有使用sendere

private void txtbox1_DoubleClick(object sender, EventArgs e)
{
    ShowMessageBox();
}

private void button1_Click(object sender, EventArgs e)
{
    ShowMessageBox();
}

private void ShowMessageBox()
{
    MessageBox.Show(txtbox1.Text);
}

Yes you can do that; 是的,你可以这么做; an event handler is just another method. 事件处理程序只是另一种方法。

However it might be worth creating a new method that shows the message box, and having both Click event handlers call that: 但是,可能值得创建一个显示消息框的新方法,并让两个Click事件处理程序调用:

private void txtbox1_DoubleClick(object sender, EventArgs e)
{
    ShowTextboxMessage();
}

private void button1_Click(object sender, EventArgs e)
{
    ShowTextboxMessage();
}

private void ShowTextboxMessage()
{
    MessageBox.Show(txtbox1.Text);
}

事件处理程序只不过是一个方法,因此您可以像任何其他方法一样调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM