MSDN:匿名方法

匿名方法

// Create a handler for a click event

button1.Click += delegate(System.Object o, System.EventArgs e)

                   { System.Windows.Forms.MessageBox.Show("Click!"); };

// Create a delegate instance

delegate void Del(int x);

 

// Instantiate the delegate using an anonymous method

Del d = delegate(int k) { /* ... */ };

例如,如果创建方法所需的系统开销是不必要的,在委托的位置指定代码块就非常有用。启动新线程即是一个很好的示例。无需为委托创建更多方法,线程类即可创建一个线程并且包含该线程执行的代码。

void StartThread()

{

    System.Threading.Thread t1 = new System.Threading.Thread

      (delegate()

            {

                System.Console.Write("Hello, ");

                System.Console.WriteLine("World!");

            });

    t1.Start();

}

如果局部变量和参数的范围包含匿名方法声明,则该局部变量和参数称为该匿名方法的外部变量或捕获变量。例如,下面代码段中的 n 即是一个外部变量:

int n = 0;

Del d = delegate() { System.Console.WriteLine("Copy #:{0}", ++n); };

匿名方法不能访问外部范围的 ref out 参数。

 

anonymous-method-block 中不能访问任何不安全代码。

// 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)

        {

            System.Console.WriteLine(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(TestClass.DoWork);

 

        // 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)

    {

        System.Console.WriteLine(k);

    }

}

posted @ 2010-06-01 08:33  gege_s  Views(273)  Comments(0)    收藏  举报