Anyone who has used JS knows function. Functions in JS can be defined as internal functions. Sometimes, in order to control the scope, or this small function is only used in this function body, you do not want to make additional definitions externally. Is there such a similar method in C? The answer is yes.
In C #, you need to use the delegate and lambda expressions. Lambda expressions can be used to implement anonymous function definitions and mount delegate events. For details, see section C # Use Lambda to hook up a delegate event.
You can create an internal function in a function in at least two ways.
First: func <>.
Type 2: Action <>
Func and action are essentially delegates. The difference is that func can output the return value, while action does not return the value. The following describes the implementationCode.
Private void outputinfo (string info) {func <int, String, string> Format = (count, message) =>{ return message + "count:" + count. tostring () ;}; action <string> showmessage = (Message) =>{ console. writeline (Message) ;}; string formatinfo = format (1, Info); showmessage (formatinfo );}
The outputinfo function defines two more functions: Format and showmessage.
The first two parameters of format are input parameters, and the third parameter is output parameters, that is, the return value. For func, there must be a return value. Therefore, func must have at least one output parameter (you can reload func in IDE ). The Lambda expression is followed by the equal sign of format. It should be noted that the parameters in lambda expressions are input parameters, which correspond one to one with the parameter types specified by func, that is, Count corresponds to the int type in func, message corresponds to the string type in func, while the content after Lambda (in braces) is specific implementation, the return value corresponds to the last parameter type of func, that is, the string type.
Showmessage parameters only include input parameters and do not return values. There is only one string type input parameter.
In practical use, the types of func and action can be flexibly defined, which greatly simplifies the large size and improves the reuse rate.