熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> .NET編程 >> 正文

MSDN:匿名方法

2022-06-13   來源: .NET編程 

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

  }

  }


From:http://tw.wingwit.com/Article/program/net/201311/12025.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.