// Create a handler for a click event buttonClick += delegate(SystemObject o SystemEventArgs e) { SystemWindowsFormsMessageBoxShow(Click!); }; // Create a delegate instance delegate void Del(int x); // Instantiate the delegate using an anonymous method Del d = delegate(int k) { /* */ }; 例如如果创建方法所需的系统开销是不必要的在委托的位置指定代码块就非常有用启动新线程即是一个很好的示例无需为委托创建更多方法线程类即可创建一个线程并且包含该线程执行的代码 void StartThread() { SystemThreadingThread t = new SystemThreadingThread (delegate() { SystemConsoleWrite(Hello ); SystemConsoleWriteLine(World!); }); tStart(); } 如果局部变量和参数的范围包含匿名方法声明则该局部变量和参数称为该匿名方法的外部变量或捕获变量例如下面代码段中的 n 即是一个外部变量 int n = ; Del d = delegate() { SystemConsoleWriteLine(Copy #:{} ++n); }; 匿名方法不能访问外部范围的 ref 或 out 参数 在 anonymousmethodblock 中不能访问任何不安全代码 // Declare a delegate delegate void Printer(string s); class TestClass { static void Main() { // Instatiate the delegate type using an anonymous method: Printer p = delegate(string j) { SystemConsoleWriteLine(j); }; // Results from the anonymous delegate call: p(The delegate using the anonymous method is called); // The delegate instantiation using a named method DoWork: p = new Printer(TestClassDoWork); // Results from the old style delegate call: p(The delegate using the named method is called); } // The method associated with the named delegate: static void DoWork(string k) { SystemConsoleWriteLine(k); } } |