[英]C# - How can I name a new event handler with number suffix using a variable?
I am creating new picture boxes and their click event handlers programmatically.我正在以编程方式创建新图片框及其单击事件处理程序。 But I can't use them seperately because I can't name them properly.但我不能单独使用它们,因为我无法正确命名它们。 I need to name the event handlers like box1_click, box2_click...我需要将事件处理程序命名为 box1_click、box2_click...
What is the simplest way to name new event handlers separately numbered with an integer?用整数分别命名新事件处理程序的最简单方法是什么?
My attempt:我的尝试:
for(i=1; i<11; i++)
{
boxes[i] = new PictureBox();
boxes[i].Name = "box" + i;
boxes[i].Click += new EventHandler( ??? );
}
You should always use the same event handler.您应该始终使用相同的事件处理程序。 Inside the handler you would decide upon the sender parameter what has to be done.在处理程序中,您将决定发送者参数必须做什么。
There are multiple ways to do that.有多种方法可以做到这一点。
You could either add the event handler as a lambda expression that calls each specific handler by reflection like this (make sure to define your handlers as public methods):您可以将事件处理程序添加为 lambda 表达式,通过像这样的反射调用每个特定处理程序(确保将您的处理程序定义为公共方法):
MethodInfo method = this.GetType().GetMethod("B_Click" + i.ToString());
boxes[i].Click += (o,e) =>
{
if (null != method)
{
method.Invoke(this, new object[2] { o, e });
}
};
... ...
public void B_Click1(object sender, EventArgs e)
public void B_Click2(object sender, EventArgs e)
etc...
Another option is to create a delegate event handler using Delegate.CreateDelegate instead of a lambda expression like this:另一种选择是使用 Delegate.CreateDelegate 而不是像这样的 lambda 表达式来创建委托事件处理程序:
MethodInfo method = this.GetType().GetMethod("B_Click" + i.ToString());
EventHandler handler = (EventHandler)Delegate.CreateDelegate(typeof(EventHandler), this, method);
boxes[i].Click += handler;
... ...
public void B_Click1(object sender, EventArgs e)
public void B_Click2(object sender, EventArgs e)
etc...
Probably the best option is to define one handler for all PictureBoxes and cast sender object as the clicked PictureBox like this:可能最好的选择是为所有图片框定义一个处理程序,并将发送者对象转换为点击的图片框,如下所示:
boxes[i].Click += B_Click;
... ...
private void B_Click(object sender, EventArgs e)
{
PictureBox clickedPictureBox = sender as PictureBox;
if (clickedPictureBox != null)
{
string name = clickedPictureBox.Name; // for example get picture box name
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.