如何在 C# 方法中设置动态参数
我为按钮 btnTrial1
编写了一个方法 Trial
:
public void trial(object sender, EventArgs e, Button btn, TextBox txt, Label lbl)
{
}
在我的应用程序中,我通过代码动态生成更多按钮、文本框和标签,并按顺序命名它们,如 btnTrial2< /code>、
txtTrial2
、lblTrial2
然后 btnTrial3
、txtTrial3
、 lblTrial3
等等。现在我想将 Trial2
设置为 trial
的 EventHandler,然后将 btnTrial3
设置为 EventHandler,依此类推。
因此,现在当我从 btnTrial1
调用方法 Trial
时,我的参数应该是:
Public void (sender, e, btnTrail1, txtTrial1, lblTrial1)
但是当我从 btnTrial2< 调用方法
Trial
时, 我的参数应该是: /code>,我的参数应该是:
Public void (sender, e, btnTrail2, txtTrial2, lblTrial2)
等等...
I have written a method trial
for button btnTrial1
:
public void trial(object sender, EventArgs e, Button btn, TextBox txt, Label lbl)
{
}
In my application, i am generating more buttons and textboxes and labels dynamically through code and naming them sequentially like btnTrial2
, txtTrial2
, lblTrial2
then btnTrial3
, txtTrial3
, lblTrial3
and so on. Now i want to set trial
as EventHandler for btnTrial2
then for btnTrial3
and so on.
So now when i call the method trial
from btnTrial1
, my parameters should be:
Public void (sender, e, btnTrail1, txtTrial1, lblTrial1)
But when i call the method trial
from btnTrial2
, my parameters should be:
Public void (sender, e, btnTrail2, txtTrial2, lblTrial2)
and so on...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您提到“动态生成它们” - 这很好,但是如果您处于循环中,您还需要注意臭名昭著的“捕获变量/循环”问题 - 特别是变量“捕获”必须在循环内;例如:(
如果,例如,
btnTrial
被声明在循环之外,就会发生不好的事情)You mention "generating them dynamically" - that is fine, but if you are in a loop you will also need to watch out for the infamous "captured variable / loop" problem - notably, the variables "captured" must be inside the loop; for example:
(if, for example,
btnTrial
was declared outside the loop, bad things would happen)为什么不让你的试用功能
然后根据发件人,使用不同的控件:
Why not make your trial function
And then based on the sender, use different controls:
两个建议:
重构
Trial()
以返回EventHandler
(或者理想情况下EventHandler
):相当比命名您的表单元素
btnTrial1
、btnTrial2
等,为什么不只制作元素列表(或一组列表)按钮
+文本框
+标签
)?然后,您只需枚举列表即可设置事件处理程序,而不是为每个事件处理程序进行硬编码。Two suggestions:
Refactor
trial()
to return anEventHandler
(or ideallyEventHandler<T>
):Rather than name your form elements
btnTrial1
,btnTrial2
, etc, why not just make lists of the elements (or a list of sets ofButton
+TextBox
+Label
)? Then you just have to enumerate over the list(s) to set up your event handlers, rather than hard-code for each.您可以为每个按钮添加:
方法,如下所示:
To each button You can add:
method like this: