代码改变世界

C#匿名方法增加、删除委托

2012-12-11 10:51  starlet  阅读(1360)  评论(0编辑  收藏  举报

匿名方法给我们带来了方便,那么如何增加删除匿名方法中附加的委托(事件)呢

一般写法:

	this.Loaded += (sender, e) =>
         {
                //Do something
         };

进化写法:

	this.Loaded += new RoutedEventHandler(FormulaAssign_Loaded);

	void FormulaAssign_Loaded(object sender, RoutedEventArgs e)
         {
            this.Loaded -= new RoutedEventHandler(FormulaAssign_Loaded);
            //do something
         }

 

优化写法:

          RoutedEventHandler eventHander = null;
          eventHander = (object sender, RoutedEventArgs e) =>
          {
                //do something
                this.Loaded -= eventHander;
          };
          this.Loaded += eventHander;