天天看點

匿名方法

    在 2.0 之前的 C# 版本中,聲明委托的唯一方法是使用命名方法。C# 2.0 引入了匿名方法。

要将代碼塊傳遞為委托參數,建立匿名方法則是唯一的方法。例如:

匿名方法

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

匿名方法

}

匿名方法

備注

匿名方法的參數的範圍是 anonymous-method-block。

在目标在塊外部的匿名方法塊内使用跳轉語句(如 goto、break 或 continue)是錯誤的。在目标在塊内部的匿名方法塊外部使用跳轉語句(如 goto、break 或 continue)也是錯誤的。

如果局部變量和參數的範圍包含匿名方法聲明,則該局部變量和參數稱為該匿名方法的外部變量或捕獲變量。例如,下面代碼段中的 n 即是一個外部變量:

匿名方法

int n = 0;

匿名方法
匿名方法

Del d = delegate() 

匿名方法

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

匿名方法

與局部變量不同,外部變量的生命周期一直持續到引用該匿名方法的委托符合垃圾回收的條件為止。對 n 的引用是在建立該委托時捕獲的。

匿名方法不能通路外部範圍的 ref 或 out 參數。

在 anonymous-method-block 中不能通路任何不安全代碼。

代碼執行個體:

下面的示例示範執行個體化委托的兩種方法:

使委托與匿名方法關聯。

使委托與命名方法 (DoWork) 關聯。

匿名方法

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

匿名方法
匿名方法
匿名方法

輸出結果: 

上一篇: 匿名對象
下一篇: 匿名管道