本文介绍了匿名方法和代表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了解为什么BeginInvoke方法不会接受匿名方法。

I try to understand why a BeginInvoke method won't accept an anonymous method.

void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    if (InvokeRequired)
    {
        //Won't compile
        BeginInvoke(delegate(object sender, ProgressChangedEventArgs e)
        { bgWorker_ProgressChanged(sender, e); });
    }

    progressBar1.Increment(e.ProgressPercentage);
}

它告诉我'无法从'匿名方法'转换为'System.Delegate 当我将匿名方法转给代理时,它会工作吗?

It tells me 'cannot convert from 'anonymous method' to 'System.Delegate' while when I cast the anonymous method to a delegate it does work ?

BeginInvoke((progressDelegate)delegate { bgWorker_ProgressChanged(sender, e); });


推荐答案

Delegate类是委托类型的基类。但是,只有系统和编译器可以从Delegate类或MulticastDelegate类显式派生。也不允许从委托类型中导出新的类型。 代理类不被视为委托类型;它是一个用于派生代理类的类。
来源 -

The Delegate class is the base class for delegate types. However, only the system and compilers can derive explicitly from the Delegate class or from the MulticastDelegate class. It is also not permissible to derive a new type from a delegate type. The Delegate class is not considered a delegate type; it is a class used to derive delegate types.Source -- MSDN

因此,需要显式转换为派生自Delegate类型。当您传递System.Delegate类型的参数的匿名方法时,您会遇到此特定的编译器错误 - 幸运的是,这是一种罕见的情况。这太灵活了。

Hence the need for the explicit cast to a derived-from-Delegate type. You'd encounter this particular compiler error when you pass an anonymous method for a parameter of System.Delegate type - fortunately this is a rare scenario. That's just too much flexibility.

delegate void MyDelegate();

  static void DoSomething_Flexible(Delegate d)
  {   d.DynamicInvoke();      }
  static void DoSomething_Usable(MyDelegate d)
  {   d();      }
  static void Main(string[] args)
  {
     // requires explicit cast else compile error Error "Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type
     DoSomething_Flexible((MyDelegate) delegate { Console.WriteLine("Flexible is here!"); });

     // Parameter Type is a .NET Delegate, no explicit cast needed here.
     DoSomething_Usable(delegate { Console.WriteLine("Usable is here!"); });
  }

有关更多信息,请访问(见Notes头后面的段落)

More on this at this page by Ian Griffith. (See the paras after the Notes header)

这篇关于匿名方法和代表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 06:03