C#匿名方法详细剖析

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

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

C#匿名方法

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

privatedelegatevoidExample6();  
 
privateint _customerId;  
privatestring _customerCode;  
 
publicint CustomerID  
{  
get { return _customerId; }  
set { _customerId = value; }  
}  
 
publicstring CustomerCode  
{  
get { return _customerCode; }  
set { _customerCode = value; }  
}  
 
privatevoid btnExample6_Click(object sender, EventArgs e)  
{  
//Populate out properties.  
this.CustomerID = 90;  
this.CustomerCode = "1337HK";  
 
//Setup the delegate/anonymous method.  
Example6 example =  
newExample6(  
delegate  
{  
this.ShowCustomer(this.CustomerID, this.CustomerCode);  
});  
 
//Execute the delegate.  
example();  
 
//Change the properties.  
this.CustomerID = 54;  
this.CustomerCode = "L4M3";  
 
//Execute the delegate again.  
// Notice that the new values are reflected.  
example();  
}  
 
privatevoid ShowCustomer(int customerId, string customerCode)  
{  
MessageBox.Show(  
String.Format("CustomerID: Customer Code: ",  
customerId, customerCode));  

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.

要注意的是,我两次调用了与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:15:19

C# 匿名方法

2009-08-20 16:28:45

C#匿名方法

2009-09-11 11:17:04

C#引用类型

2009-08-31 17:26:32

C#异常处理

2009-09-18 10:00:17

C#数组操作

2009-09-03 16:58:49

C#内存管理

2009-08-20 16:25:59

C# 匿名方法

2009-09-01 11:04:59

C#调用扩展方法

2009-08-21 18:01:32

C#匿名方法

2009-08-27 17:47:18

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-09-10 17:37:01

C# get post

2009-08-26 15:46:01

C#匿名类型

2009-07-31 14:08:54

C# 匿名函数
点赞
收藏

51CTO技术栈公众号