最近搞C#遇到了EventHandler 参数传递问题,实际就是匿名函数的应用,话不多少,直接上代码:
1.无需传参写法:
//这段代码是无需传参
treeView1.ContextMenuStrip = new ContextMenuStrip();
ToolStripMenuItem tmiEditRoutStation = new ToolStripMenuItem("数据定位");
tmiEditRoutStation.Click += new EventHandler(zoomToTheLayer);//此处不需传参
treeView1.ContextMenuStrip.Items.Add(tmiEditRoutStation);
treeView1.ContextMenuStrip.Show(e.X, e.Y);
2.需要传参写法:本例主要是把int型handlerNum传给函数zoomToTheLayer
//传参
treeView1.ContextMenuStrip = new ContextMenuStrip();
ToolStripMenuItem tmiEditRoutStation = new ToolStripMenuItem("数据定位");
tmiEditRoutStation.Click += delegate(object sender1, EventArgs e1) { zoomToTheLayer(sender, e, handlerNum); };//匿名传参
treeView1.ContextMenuStrip.Items.Add(tmiEditRoutStation);
treeView1.ContextMenuStrip.Show(e.X, e.Y);
private void zoomToTheLayer(object sender, EventArgs e, int handlerNum)
{
MessageBox.Show(handlerNum.toString());//这个函数主要是函数实现
}