C#匿名方法详细剖析

开发 后端
这里介绍在C#匿名方法里的外部变量在创建C#匿名方法的时候被引用。这意味着对这些变量的任何更改都会在匿名函数访问变量的时候被反映出来。

C#语言还是比较常见的东西,这里我们主要介绍C#匿名方法,包括介绍当C#匿名方法不需要带参数的时候,后面的括号是可选的等方面。

C#匿名方法

这是对变量范围的扩展。但是,下面例子说明了匿名参数还能够在它们的代码块之外执行命名方法:

  1. privatedelegatevoidExample6();  
  2.  
  3. privateint _customerId;  
  4. privatestring _customerCode;  
  5.  
  6. publicint CustomerID  
  7. {  
  8. get { return _customerId; }  
  9. set { _customerId = value; }  
  10. }  
  11.  
  12. publicstring CustomerCode  
  13. {  
  14. get { return _customerCode; }  
  15. set { _customerCode = value; }  
  16. }  
  17.  
  18. privatevoid btnExample6_Click(object sender, EventArgs e)  
  19. {  
  20. //Populate out properties.  
  21. this.CustomerID = 90;  
  22. this.CustomerCode = "1337HK";  
  23.  
  24. //Setup the delegate/anonymous method.  
  25. Example6 example =  
  26. newExample6(  
  27. delegate  
  28. {  
  29. this.ShowCustomer(this.CustomerID, this.CustomerCode);  
  30. });  
  31.  
  32. //Execute the delegate.  
  33. example();  
  34.  
  35. //Change the properties.  
  36. this.CustomerID = 54;  
  37. this.CustomerCode = "L4M3";  
  38.  
  39. //Execute the delegate again.  
  40. // Notice that the new values are reflected.  
  41. example();  
  42. }  
  43.  
  44. privatevoid ShowCustomer(int customerId, string customerCode)  
  45. {  
  46. MessageBox.Show(  
  47. String.Format("CustomerID: Customer Code: ",  
  48. customerId, customerCode));  

要注意的是,我两次调用了与C#匿名方法相关联的委托。你可能会发现一个很有趣的事情:在这些调用中,方法会输出两组不同的值。这是因为用在C#匿名方法里的外部变量在创建C#匿名方法的时候被引用。这意味着对这些变量的任何更改都会在匿名函数访问变量的时候被反映出来。

你可能还注意到在这个实例里委托关键字后面没有括号。当C#匿名方法不需要带参数的时候,后面的括号是可选的。

【编辑推荐】

  1. C#类和结构简单介绍
  2. C# explicti和implicit详解
  3. C#编写ActiveX控件详细介绍
  4. C# StringBuilder和String浅析
  5. C#别名指示符学习经验
责任编辑:佚名 来源: cnblogs
相关推荐

2009-08-27 17:14:36

C# Socket

2009-08-20 16:28:45

C#匿名方法

2009-08-20 16:15:19

C# 匿名方法

2009-09-11 11:17:04

C#引用类型

2009-08-31 17:26:32

C#异常处理

2009-09-03 16:58:49

C#内存管理

2009-09-18 10:00:17

C#数组操作

2009-08-20 16:25:59

C# 匿名方法

2009-08-21 18:01:32

C#匿名方法

2009-08-27 17:47:18

C#匿名方法作为参数传

2009-09-01 11:04:59

C#调用扩展方法

2009-09-04 11:06:40

C#访问修饰符

2009-08-31 16:29:21

C#控制输入法

2009-09-07 13:42:56

C# Pop3类

2009-08-28 15:38:49

C#实现断点续传

2009-08-10 17:25:58

C#匿名类型

2009-09-09 14:04:18

C# XML解析XML解析方法

2009-07-31 14:08:54

C# 匿名函数

2009-08-26 15:46:01

C#匿名类型

2009-09-10 17:37:01

C# get post
点赞
收藏

51CTO技术栈公众号