委托是一个类,它定义了方法的类型,使得可以将方法当作另一个方法的参数来进行传递,这种将方法动态地赋给参数的做法,可以避免在程序中大量使用If-Else(Switch)语句,同时使得程序具有更好的可扩展性。
推荐一篇文章:点击打开链接 ,此篇由浅入深的介绍了delegate→event,参考价值很高。
以下是事件封装委托变量的用例:
public MainWindow()
{
InitializeComponent();
scontextmenu xx = new scontextmenu();
xx.addMenu("xxxx");
xx.addMenu("yyy");
xx.ONMENUITEMcLICK += new scontextmenu.MenuItemClickedHandler(xx_ONMENUITEMcLICK);
this.ContextMenu = xx;
}
void xx_ONMENUITEMcLICK(string txt)
{
MessageBox.Show(txt);
}
class scontextmenu : ContextMenu
{
Dictionary<string, int> dict = new Dictionary<string, int>();
public scontextmenu()
{
}
public void addMenu(string txt)
{
MenuItem item = new MenuItem();
item.Header = txt;
item.Click += new System.Windows.RoutedEventHandler(item_Click);
this.Items.Add(item);
}
void item_Click(object sender, System.Windows.RoutedEventArgs e)
{
MenuItem item = (MenuItem)sender;
var headtext = (string)item.Header;
if (ONMENUITEMcLICK != null)
{
ONMENUITEMcLICK(headtext);
}
//throw new NotImplementedException();
}
public delegate void MenuItemClickedHandler(string txt);
public event MenuItemClickedHandler ONMENUITEMcLICK;
}