【已更新最新开发文章,点击查看详细】

Lambda 表达式。

这里是两个示例:

// 为单击事件创建处理程序
button1.Click += delegate(System.Object o, System.EventArgs e)
                 { System.Windows.Forms.MessageBox.Show("Click!"); };
// 创建一个委托.
delegate void Del(int x);

// 使用匿名方法实例化委托
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();
}

备注

匿名方法的参数范围为匿名方法块。

如果目标在匿名方法块之内,匿名方法块外具有 gotobreakcontinue 等跳转语句也是一种错误。

例如,在如下代码段中,n 是一个外部变量:

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

不同于本地变量,已捕获的变量的生存期一直延伸至引用匿名方法的委托具有垃圾回收资格为止。

out 参数。

无法在匿名方法块内访问任何不安全代码。

is 运算符左侧使用匿名方法。

示例

如下示例演示实例化委托的两种方式:

  • 将委托与匿名方法相关联。

  • 将委托与命名方法 (DoWork) 相关联。

在每一种情况下,调用委托时均显示一条消息。

// 定义委托.
delegate void Printer(string s);

class TestClass
{
    static void Main()
    {
        // 使用匿名方法实例化委托类型
        Printer p = delegate(string j)
        {
            System.Console.WriteLine(j);
        };

        // 匿名委托调用的结果
        p("The delegate using the anonymous method is called.");

        // 使用命名方法“DoWork”的委托实例化
        p = DoWork;

        // 传统方式委托调用的结果
        p("The delegate using the named method is called.");
    }

    // 与命名委托关联的方法。
    static void DoWork(string k)
    {
        System.Console.WriteLine(k);
    }
}
/* 输出:
    The delegate using the anonymous method is called.
    The delegate using the named method is called.
*/

其他更详细的技术请参考:

 

【已更新最新开发文章,点击查看详细】

相关文章:

  • 2021-10-07
  • 2021-10-30
  • 2021-06-14
  • 2021-05-16
  • 2022-12-23
  • 2021-09-19
  • 2021-08-03
猜你喜欢
  • 2021-12-26
  • 2022-01-21
  • 2021-10-15
  • 2021-11-05
  • 2022-02-22
  • 2021-11-16
  • 2021-06-12
相关资源
相似解决方案