尝试使用Reflection
,例如按名称调用对象方法:
Type yourType= yourObject.GetType();
MethodInfo theMethod = thisType.GetMethod("MenuOption_xxx");
theMethod.Invoke(this, null);
您可以将 menusTag
属性设置为标识符:
menuItem1.Tag = "X"; // name or id of this menuitem
menuItem2.Tag = "XX";
menuItem3.Tag = "XXX";
然后设置Click
事件:
menuItem1.Click += MenuItem_Click;
menuItem2.Click += MenuItem_Click;
menuItem3.Click += MenuItem_Click;
关于Click
事件:
private void MenuItem_Click(object sender, EventArgs e)
{
var id = (String) ((MenuItem))sender.Tag;
// use reflection:
Type yourType= yourObject.GetType();
MethodInfo theMethod = thisType.GetMethod(String.Format("MenuOption_{0}", id));
theMethod.Invoke(this, null);
}
public void MenuOption_X
{
...
}
public void MenuOption_XX
{
...
}