如何在 c# 方法中设置动态参数

本文关键字:设置 动态 参数 方法 | 更新日期: 2023-09-27 18:05:43

我为按钮btnTrial1编写了一个方法trial

public void trial(object sender, EventArgs e, Button btn, TextBox txt, Label lbl)
{
}

在我的应用程序中,我通过代码动态生成更多的按钮、文本框和标签,并按顺序命名它们,如btnTrial2txtTrial2lblTrial2然后btnTrial3txtTrial3lblTrial3等。现在我想trial设置为 btnTrial2 的事件处理程序,然后是btnTrial3,依此类推。

所以现在当我从btnTrial1调用方法trial时,我的参数应该是:

Public void (sender, e, btnTrail1, txtTrial1, lblTrial1)

但是当我从btnTrial2调用方法trial时,我的参数应该是:

Public void (sender, e, btnTrail2, txtTrial2, lblTrial2)

等等...

如何在 c# 方法中设置动态参数

btnTrial1.YourEvent += (sender, args) => trial(sender, args,
        btnTrial1, txtTrial1, lblTrial1);
btnTrial2.YourEvent += (sender, args) => trial(sender, args,
        btnTrial2, txtTrial2, lblTrial2);

提到"动态生成它们"——这很好,但如果你在一个循环中,你还需要注意臭名昭著的"捕获变量/循环"问题——值得注意的是,"捕获"的变量必须在循环内;例如:

for(int i = 1 ; i <= 10 ; i++) {
    var btnTrial = ...
    var txtTrial = ...
    var lblTrial = ...
    btnTrial.YourEvent += (sender, args) => trial(sender, args,
        btnTrial, txtTrial, lblTrial);
}

(例如,如果在循环声明btnTrial,就会发生不好的事情(

为什么不让你的试用函数

public void trial(object sender, EventArgs e)
{
}

然后根据发件人,使用不同的控件:

public void trial(object sender, EventArgs e)
{
    Button btn;
    TextBox txt;
    Label lbl;
    if (sender == btnTrial1){
        btn = btnTrail1;
        txt = txtTrial1;
        lbl = lblTrial1;
    }
    if (sender == btnTrial2){
        btn = btnTrail2;
        txt = txtTrial2;
        lbl = lblTrial2;
    }
    if (sender == btnTrial3){
        btn = btnTrail3;
        txt = txtTrial3;
        lbl = lblTrial3;
    }
    //rest of the method
}

两个建议:

  1. 重构trial()以返回EventHandler(或理想情况下EventHandler<T>(:

    public EventHandler GetTrialEventHandler(Button btn, TextBox txt, Label lbl)
    {
         return (sender, args) =>
         {
             // Do something with btn, txt, lbl
         };
    }
    
  2. 与其将表单元素命名为 btnTrial1btnTrial2 等,不如只列出元素(或Button + TextBox + Label 集的列表(?然后,只需枚举列表即可设置事件处理程序,而不是为每个事件处理程序进行硬编码。

到每个按钮 您可以添加:

this.button.Click += new System.EventHandler(this.button_Click);

方法如下:

private void button_Click(object sender, EventArgs e)
{
    String name = (sender as Control).Name;
    int number = Int32.Parse(name.Substring(name.Length-1));
    trial(sender, e, this.Controls["btnTrial"+number], this.Controls["txtTrial"+number], Controls["lblTrial"+number]);
}