I have two methods with 开发者_StackOverflow社区the following signatures
void Invoke(Action method)
void Foo()
What is the difference between the following two lines of code?
Invoke(new Action(Foo));
and
Invoke(Foo);
and is the second line allowed?
Thanks
Why don't you try it?
If the signature of your method is
void Invoke(Action objAction)
then it is legal. And then the 2 calls are the same. The feature for this is called "implicit method group conversion".
Your signature is is "Invoke(Delegate method)" (capitalized 'D'), isn't it?
Only the first line constructing the Action explicitly works.
The reason behind this: Delegate is the base class for all delegates. It represents a delegate with an unknown return value and unknown number and type of parameters. You can only invoke it using DynamicInvoke.
So the compiler does not know, which actual type of delegate to use when passing only a method name: "Invoke(Foo);". It could be an Action, but also another delegate with the same signature as Foo.
However, if you explicitly create the delegate, it can be implicitly converted to Delegate and therefore the code compiles.
精彩评论