简体   繁体   中英

Difference between sending an anonymous function vs. Func/Action to another function with a Delegate parameter?

If Action is a delegate as stated on MDN:

public delegate void Action()

  • Why can it be passed to a non-delegate type as Delegate?
  • Why can't an anonymous function be passed then? (I read that a lambda creates an anonymous delegate as if the function was created with delegate {} )

TestA (new Action (delegate { return; })); // Right.
TestA (delegate { return; }); // Wrong.
TestB (delegate { return; }); // Right.
TestB (() => { return; }); // Right.

public void TestA(Delegate del) {
  // stuff...
}

public void TestB(Action callback) {
  TestB (callback);
}

All delegates inherit from Delegate , so you can pass any delegate to a method accepting a Delegate .

Why can't an anonymous function be passed then?

Because it doesn't have a delegate type. It's an anonymous method, but the compiler doesn't know what delegate that anonymous method should be. (The use of the delegate keyword here, when creating an anonymous method, is confusing. You're not actually creating an anonymous delegate, you're creating an anonymous method.)

The expression doesn't compile because the compiler always needs to be able to figure out what the type of any expression is, and for anonymous methods (and lambdas) it needs to do so from context. When the method is a Delegate , it can't figure out which delegate it's supposed to be, so it fails. When you pass it to Action , it knows what action it's supposed to be, and it's compatible, so, success.

(I read that a lambda creates an anonymous delegate as if the function was created with delegate {})

  1. That's an anonymous method, but not a lambda.
  2. An anonymous method, or a lambda, never creates an anonymous delegate in C#. It does in VB.NET (perhaps you heard that and thought it applied to C#?), but in C# there is no such thing as an anonymous delegate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM