Lambda expressions and function pointers

Source: Internet
Author: User

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 ".

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.