C#匿名方法怎么用

发布时间:2021-12-01 13:49:39 作者:小新
来源:亿速云 阅读:128

这篇文章将为大家详细讲解有关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));  }

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

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

关于“C#匿名方法怎么用”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

推荐阅读:
  1. 委托三------------多播委托与匿名方法
  2. [C# 基础知识系列]专题十一:匿名方法解析

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

上一篇:C#中构造线性表的类有哪些

下一篇:怎样使SQL用户只能看到自己拥有权限的库

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》