Generic delegated Learning (func and action)

Source: Internet
Author: User

Func <tparams, tresult>

Generic delegation. Tparams is the parameter type of the method encapsulated by this delegate. It can have 0 or more but cannot exceed 4 tresult return value types.

You can use this delegate to indicate a method that can be passed as a parameter without explicitly declaring a custom delegate. This method must correspond to the method signature defined by this delegate. That is to say, the encapsulated method must have a parameter passed to it through a value and must return a value.

Example 1:

Static void main (string [] ARGs)
{

Func <string, string> functest = demo;

Console. writeline (functest ("aaaaaa "));

}

Static string demo (string S)
{
Return S. toupper ();
}

// Output aaaaaa

This delegate can also be used with anonymous methods!

Example 2:

Func <string, string> funtest = delegate (string s) {return S. toupper ();};

Console. writeline (functest ("aaaaaa "));

The output result is the same as that in Example 1.

 

You can also assign a Lambda expressionFuncDelegate

Example 3

 

Func <string, string> functest = s => S. toupper ();

Console. writeline (functest ("aaaaaa "));

 

The output results are the same. Lambda expressions are more concise.

 

But what if there is no return value? Because the func delegate must have a return value, you need to use action.

Action <tparams>

This delegate method has no return value. The tparams parameter type list can only be 1 to 4

Example:

Static void main (string [] ARGs)
{

Action <string> actiontest = demo2;
Actiontest ("Zhang ");

}

Static void demo2 (string S)
{
Console. writeline (S. toupper ());
}

Output Zhang

(Action cannot be used with Lambda expressions like func)

 

 

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.