What it means to have body in delegates declaration?
-
27-06-2021 - |
Question
I have just seen following code:
class X
{
static Action Ac()
{
return ..some other code
}
}
What does it mean? I have never seen a delegate with its body declared.
La solution
That's not an Action
delegate with its body declared. That's a static method of the X
class called Ac()
, with a return type of Action
; that is, it's a class method that returns an Action
delegate. The body presumably creates an Action
object to return from the method.
To put it another way: it is a regular static method, which happens to return Action
instead of something like string
or int
.
Autres conseils
Delegate object which references anonymous method is declared something like (using old syntax and omitting lambda notation):
Action<int> action = delegate (int x) {
//this is a body of anonymous method
//which is referenced by a delegate object action of type Action<int>
Console.WriteLine (x);
};
And than called like:
action(5);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow