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#匿名方法不需要带参数的时候,后面的括号是可选的。
【编辑推荐】