C# 匿名方法

简介:

         要将代码块传递为委托参数,创建匿名方法即可实现。简单的理解就是本来要写个函数实现某个功能,用匿名方法即可直接实现某个功能,省去函数名。

 

使用:

1. 启动新线程。 无需为委托创建更多方法,线程类即可创建一个线程并且包含该线程执行的代码。

void StartThread()
{
    System.Threading.Thread t1 = new System.Threading.Thread
      (delegate()
            {
                System.Console.Write("Hello, ");
                System.Console.WriteLine("World!");
            });
    t1.Start();
}

 

 2.注意事项

匿名方法的参数的范围是“匿名方法块”。

如果目标在块外部,那么,在匿名方法块内使用跳转语句(如 goto、 break 或 continue)是错误的。 如果目标在块内部,在匿名方法块外部使用跳转语句(如 goto、break 或 continue)也是错误的。

如果局部变量和参数的范围包含匿名方法声明,则该局部变量和参数称为该匿名方法的“外部”变量。

外部变量的引用n被认为是捕获在创建委托时。 与本地变量不同,捕获的变量的生存期内扩展,直到引用该匿名方法委托被垃圾回收。

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

在“匿名方法块”中不能访问任何不安全代码。

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

 

 3.实例化委托,使委托与匿名方法关联和使委托与命名方法 (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 = new Printer(TestClass.DoWork);

        // 匿名委托传入参数
        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);
    }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值