在另一个事件处理程序中调用事件处理程序? [英] calling a event handler within another event handler?
本文介绍了在另一个事件处理程序中调用事件处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是简短的示例代码:
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);
}
但是对于最佳实践和代码可读性,这样做可能更好,尤其是当您不使用发件人
和 e
时:
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
:
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);
}
这篇关于在另一个事件处理程序中调用事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文