Guess the following two parts: C #CodeWhat is the output:
(1)
Static Void Main ( String [] ARGs)
{
Print (23 );
Console. readkey ();
}
Static Action Print (IntN)
{
Return ( ) =>
{
Console. writeline (N );
} ;
}
(2)
Static Void Main ( String [] ARGs)
{
Print () (23 );
Console. readkey ();
}
Static Action <Int> Print ()
{
Return (IntN ) =>
{
Console. writeline (N );
} ;
}
If you are a C ++ProgramPersonnel, maybe the above is not a strange usage, because the function pointer can be used in C ++, as shown below:
# Include < Iostream >
Using Namespace STD;
Void Print ( Int A );
Int Main ()
{
Typedef Void ( * Action )( Int A ); // Define a function pointer type named action. The delegate in C # is similar.
Action action = Print;
( * Action) (23 );// Note that the usage here is similar to that in (2.
Getchar ();
Return 0 ;
}
Void Print ( Int A)
{
Cout<A<Endl;
}
But C # does not, but C # has a delegate. it plays a similar role. The Lambda expression value is a delegate type, and there is no output in the first example. The print function simply returns a delegate (Action type ), it can also be seen as pointing to function funtion (){Console. writeline (n);} function pointer.However, the function itself is not executed here. If you read the second example, you may be more clear about this. The second example calls the function pointed to by the Action <int> in one sentence.
However, I still do not recommend the second method because it is not easy to read and not "elegant ".