如何在 c# 方法中设置动态参数
本文关键字:设置 动态 参数 方法 | 更新日期: 2023-09-27 18:05:43
我为按钮btnTrial1
编写了一个方法trial
:
public void trial(object sender, EventArgs e, Button btn, TextBox txt, Label lbl)
{
}
在我的应用程序中,我通过代码动态生成更多的按钮、文本框和标签,并按顺序命名它们,如btnTrial2
、txtTrial2
、lblTrial2
然后btnTrial3
、txtTrial3
、lblTrial3
等。现在我想trial
设置为 btnTrial2
的事件处理程序,然后是btnTrial3
,依此类推。
所以现在当我从btnTrial1
调用方法trial
时,我的参数应该是:
Public void (sender, e, btnTrail1, txtTrial1, lblTrial1)
但是当我从btnTrial2
调用方法trial
时,我的参数应该是:
Public void (sender, e, btnTrail2, txtTrial2, lblTrial2)
等等...
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
}
两个建议:
-
重构
trial()
以返回EventHandler
(或理想情况下EventHandler<T>
(:public EventHandler GetTrialEventHandler(Button btn, TextBox txt, Label lbl) { return (sender, args) => { // Do something with btn, txt, lbl }; }
-
与其将表单元素命名为
btnTrial1
、btnTrial2
等,不如只列出元素(或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]);
}