C# 关于匿名委托的一些注意点

以下是摘录MSDN中的说明:

在 2.0 之前的 C# 版本中,声明委托的唯一方法是使用命名方法。C# 2.0 引入了匿名方法,而在 C# 3.0 及更高版本中,Lambda 表达式取代了匿名方法,作为编写内联代码的首选方式。不过,本主题中有关匿名方法的信息同样也适用于 Lambda 表达式。有一种情况下,匿名方法提供了 Lambda 表达式中所没有的功能。匿名方法使您能够省略参数列表,这意味着可以将匿名方法转换为带有各种签名的委托。这对于 Lambda 表达式来说是不可能的。

要将代码块传递为委托参数,创建匿名方法则是唯一的方法。这里是两个示例:

  

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

delegatevoidDel(int x);

// Instantiate the delegate using an anonymous method

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

通过使用匿名方法,由于您不必创建单独的方法,因此减少了实例化委托所需的编码系统开销。

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

  

voidStartThread(){

System.Threading.Thread t1 =newSystem.Threading.Thread (delegate() { System.Console.Write("Hello, ");

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

t1.Start();

}

备注

匿名方法的参数的范围是“匿名方法块”。(尤为注意

如果目标在块外部,那么,在匿名方法块内使用跳转语句(如 goto、break 或 continue)是错误的。如果目标在块内部,在匿名方法块外部使用跳转语句(如gotobreakcontinue)也是错误的。(唯一使用情况:目标与跳转语句都在匿名方法内部,两个皆在外

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

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

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

与局部变量不同,捕获变量的生命周期一直持续到引用该匿名方法的委托符合垃圾回收的条件为止。对n的引用是在创建该委托时捕获的。

匿名方法不能访问外部范围的 ref 或 out 参数。(个人标注:比如 参数使用ref,out修饰的,另外方法中调用方法

在“匿名方法块”中不能访问任何不安全代码。(个人标注:一般如unsafe代码段,指针

在 is 运算符的左侧不允许使用匿名方法。(个人标注:包括了含返回值的匿名委托

示例

下面的示例演示实例化委托的两种方法:

使委托与匿名方法关联。

使委托与命名方法 (DoWork) 关联。

两种方法都会在调用委托时显示一条消息。

delegatevoidPrinter(string s);

classTestClass
{
   staticvoidMain() {
        // 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 =newPrinter(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:
   staticvoidDoWork(string k)
    {
        System.Console.WriteLine(k);
    }
}
输出:

The delegate using the anonymous method is called.

The delegate using the named method is called.

 

红色标注部分是很重要的,我之前做一个GPS解析地理位置时,使用了WebRequest.BeginGetResponse 方法 的匿名委托时,就出现了这个问题,所以标注出来,提醒大家!

http://hi.baidu.com/jiang_yy_jiang/blog/item/5defaa59f0c7e63f2934f0a2.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值