Warning: Undefined array key 0 in /www/wwwroot/w/show/success.php on line 261

Warning: Trying to access array offset on value of type null in /www/wwwroot/w/show/success.php on line 261
_higrid.net-嗨网
当前位置:嗨网首页>书籍在线阅读

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

Warning: Undefined array key 0 in /www/wwwroot/w/show/success.php on line 266

Warning: Trying to access array offset on value of type null in /www/wwwroot/w/show/success.php on line 266

Warning: Undefined array key 0 in /www/wwwroot/w/show/success.php on line 266

Warning: Trying to access array offset on value of type null in /www/wwwroot/w/show/success.php on line 266

10.6.1 匿名方法

要将代码块传递为委托参数,创建匿名方法则是唯一的方法。匿名方法就是为了将代码块传递为委托参数,因此也有人将其称为匿名委托。使用C#的匿名方法可以使委托及事件的代码编写更加精简、高效。一般情况下,事件注册事件处理方法,需要首先定义这个方法,如果该方法仅用于订阅特定的事件,则可使用代码更加简明的匿名方法。下面将【范例10-5】改成匿名方法订阅事件。

【范例10-5】中Heater类不变,去掉Alarm类和Display类,使用匿名方法订阅事件修改Main方法中的代码如下,运行结果不变(拓展代码10-5.txt)。

01  static void Main(string[] args)
02  {
03          Heater heater = new Heater();             //创建热水器对象heater
04          heater.BoilEvent+= delegate(int param) {  //水快开时报警的匿名方法
05                  Console.WriteLine("Alarm:嘀嘀嘀,水已经 {0} 度了:", param);
06          };
07          heater.BoilEvent += delegate(int param)
08          {        //显示水温的匿名方法
09                  Console.WriteLine("Display:水快烧开了,当前温度:{0}度。", param);
10          };  
11          heater.BoilWater();                       //烧水,会自动调用订阅过的对象方法
12          Console.ReadKey();
13  }


Warning: Undefined array key 0 in /www/wwwroot/w/show/success.php on line 276

Warning: Trying to access array offset on value of type null in /www/wwwroot/w/show/success.php on line 276

Warning: Undefined array key 0 in /www/wwwroot/w/show/success.php on line 276

Warning: Trying to access array offset on value of type null in /www/wwwroot/w/show/success.php on line 276