rt

解决方案 »

  1.   


    参考C#多个方法的关联就和命名方法一样,将多个匿名方法与同一个委托进行关联是可能的。这在很多情况下会非常有用——首先想到的是把一个简单的处理程序添加给按钮的点击事件。下面的代码显示了一个委托,它同时带有与之相关联一个匿名方法和一个命名方法:privatedelegatevoidExample4(stringfirstName,stringlastName);   privatevoidbtnExample4_Click(objectsender,EventArgse)  {  //Setupourparameters.  stringparameter1="Zach";  stringparameter2="Smith";   //CreateaninstanceoftheExample4delegatewithan  //anonymousmethod.  Example4example=  newExample4(  delegate(stringfirstName,stringlastName)  {  MessageBox.Show("Example4:"+firstName+""+lastName);  });   //Addanothermethodtothedelegate-thistime  //anamedmethod.  example+=newExample4(Example4NamedMethod);   //Executethedelegate.  example(parameter1,parameter2);  }   privatevoidExample4NamedMethod(stringfirstName,stringlastName)  {  MessageBox.Show("Example4Method:"+firstName+""+lastName);  }