Original address: https://www.cnblogs.com/ultimateWorld/p/5608122.html
Action and Func are built-in delegates that are added to the. NET class library for a simpler and more convenient use of delegates.
When you initially use a delegate, you need to define the delegate type, and then define a function that conforms to the signature of the delegate type.
Before calling, you declare and create a delegate object that associates the specified function with the delegate.
As Example 1:
public delegate int Math (int param1,int param2); define delegate type
public int Add (int param1,int param2)//define the same signature function
{
Return param1+param2;
}
Math math;//Declaration Delegate
Math=new Math (ADD), creating a delegate object, associating with the specified
Math (3,4);//Call delegate function
If you need a delegate type of three, four arguments, you need to define the delegate type again. A simple delegate invocation requires that the delegate type be defined multiple times according to the signature, and Microsoft has introduced a built-in delegate type that simplifies this:
Action and Func, which simplifies these unnecessary operations.
Built-in delegate types, as the name implies, action and Func are themselves defined delegate types. The difference between the two delegate types is that the action delegate signature does not provide a return type, and Func provides a return type.
The Action delegate has action<t>, action<t1,t2>, Action<t1,t2,t3>, ... Action<t1,...... T16> up to 16 overloads, where incoming parameters are in the generic type parameter T, covering almost all of the delegate types that may exist without a return value. Func has func<tresult>, Func<t,tresult> FUNC<T1,T2,T3......,TRESULT>17 types of overloads, T1 ... T16 is the entry and exit parameter, and TResult is the return type.
Example 1 through simple modification:
Func<int,int,int> math=add;//specifying a delegate object and associating functions
Math (3,4);//Call delegate function
You do not need to define a direct Declaration association.
Since it is a delegate type, it can also be used in conjunction with anonymous functions, or with lambda expressions:
Anonymous functions:
func<int,int,int> math=delegate (int param1,int param2)
{
Return param1+param2;
}
Lambda:
Func<int,int,int> math= (PARAM1,PARAM2) =
{
Return param1+param2;
}
The action is used just like the above func, except that the return type is missing and the delegate function is called directly.
public void Add (int param1,int param2)
{
MessageBox.Show ((PARAM1+PARAM2). ToString ());
}
When you encounter a delegate function call of this class, we can use the action directly:
Action<int,int> Math=add;
Math (3,4);
The above is a simple understanding and introduction of action and Func, the code in the document is hand-knocked to show a schematic, if there is a problem, please understand.
"Go" understanding of Func and action in C #