c# - 将事件处理程序设置为参数
问题描述
我需要做这样的事情:
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;
}
我怎么能这样做???我可以这样做吗???
解决方案
你可以使用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);
推荐阅读
- javascript - 无法使用 Mongoose 连接到 MongoDB
- php - 准备好的批次/批量插入 w/ 生成的列
- reactjs - 在功能组件中将数据从子级传递给父级
- r - 根据列值在 R 中生成多个图的更简单代码?
- amazon-web-services - 如何使用 vscode aws 扩展编辑 lambda (go)
- python - 如何在使用 Tomtom 进行地理编码时使用谷歌转换地理编码?(Python?
- python - 异常:AttributeError:“DefaultAzureCredential”对象没有使用 Azure Function 和 Python 的属性“signed_session”
- java - 我如何从界面中引用它
- flutter - 在自定义 Painter Flutter 中包装段落文本
- javascript - 通过 JS 应用多个 RegExp .match() 时如何阻止页面死机?