委托与匿名方法

 

反汇编了一段程序,重新编译时,下面的代码不能通过:

private void OnFrameChanged(object o)
        {
             
             base.Dispatcher.BeginInvoke(DispatcherPriority.Render, delegate
             {
                 this.ChangeSource();
             });
             
        }
        private void ChangeSource()
        {
            base.Source = this.animatedBitmap.Frames[this._nCurrentFrame++];
            this._nCurrentFrame %= this.animatedBitmap.Frames.Count;
            if (this._nCurrentFrame == 0)
            {
                this._nCurrentFrame = 1;
            }
        }

 

红色的地方,提示“错误 1 无法将 匿名方法 转换为类型“System.Delegate”,因为它不是委托类型” 

BeginInvoke的声明:
public DispatcherOperation BeginInvoke(
    DispatcherPriority priority,
    Delegate method
)

 

 

BeginInvoke的第二个参数是委托类型,匿名方法难道不是委托类型?代码改成下面,则错误消失:

private void OnFrameChanged(object o)
		{
			 Action a = ChangeSource;
			 base.Dispatcher.BeginInvoke(DispatcherPriority.Render,a );
		}

  或者

private void OnFrameChanged(object o)
		{
			 
			 base.Dispatcher.BeginInvoke(DispatcherPriority.Render, new  Action ( delegate  {
			     this.ChangeSource();
			 }));
		 
		}

  Action是在System中声明的委托,用匿名方法生成一个Action实例,则错误消失,可见,匿名方法和委托关系很密切,但绝对不是一回事!再查C#语言规格,才想起来,错误 在哪。委托是一种类型,和int,bool一样,意思是函数指针,而匿名方法只是一个方法(函数),不是指针。



 

posted on 2012-11-26 10:13  freecoder  阅读(522)  评论(0编辑  收藏  举报

导航