首页 > 解决方案 > 将事件处理程序设置为参数

问题描述

我需要做这样的事情:

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 语句的文本框,所以我想做这样的事情:

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

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

标签: c#events

解决方案


你可以使用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);

推荐阅读