将事件处理程序设置为参数

时间:2018-06-13 07:23:06

标签: c# events

我需要做这样的事情:

if ((sender as TextBox).Equals(TextBox1))
{
    TextBox2.TextChanged -= TextBox2_TextChanged;
    TextBox2.Text = TextBox1.Text;
    TextBox2.TextChanged -= TextBox2_TextChanged;
}
else if ((sender as TextBox).Equals(TextBox3))
{
    TextBox4.TextChanged -= TextBox4_TextChanged;
    TextBox4.Text = TextBox3.Text;
    TextBox4.TextChanged -= TextBox4_TextChanged;
}

但是对于if-else语句我有太多TextBox,所以我想做这样的事情:

public void My_function(TextBox textbox1, TextBox textbox2, string event_name)
{
    textbox2.TextChanged -= event_name;
    textbox2.Text = textbox1.Text;
    textbox2.TextChanged -= event_name;
}

我该怎么做?我可以这样做吗?

1 个答案:

答案 0 :(得分:1)

您可以使用EventHandler MSDN

 private void textBox1_TextChanged(object sender, EventArgs e)
 {
      textBox1.Text = "hello";
 }

 public static void My_function(TextBox textbox1, EventHandler handler)
 {
    textbox1.TextChanged -= handler;
 }

并调用该函数只需执行

My_function(textBox1, textBox1_TextChanged);