Func, Action
Introduction and usage
Func is a type of Delegate, which is added in 3.5. in 2.0, we use the delegate to use delegate, and func is located in system. in the core namespace, the use of delegation can improve the efficiency. For example, using it in reflection can compensate for the performance loss caused by reflection.
Action <t> and func <t, tresult> have the same functions, but action <t> has no return type,
Func <t, t, result>: There are parameters and return types.
Action, no response or parameter is returned,
Func <t, tresult>
Can be divided into the following forms:
1. Func <t, tresult>
2. Func <t, T1, tresult>
3. Func <t, T1, T2, tresult>
4. Func <t, T1, T2, T3, tresult>
5. Func <t, T1, T2, T3, T4, tresult>
The meaning of each parameter is described separately, and tresult indicates
The types of the Methods returned by the delegate. T, T1, T2, T3, and T4 indicate the parameter types of the methods called by the delegate,
The following is an example:
Func <int, bool> myfunc = NULL; // all variables
Myfunc = x => checkisint32 (X );
// Lambda expressions are used for the delegate encapsulation method.
Private bool checkisint32 (int pars) // encapsulated Method
{
Return pars = 5;
}
Bool OK = myfunc (5); // call the delegate
Msdn: http://msdn.microsoft.com/zh-cn/library/bb534303 (vs.95). aspx
But what if we need to encapsulate the method without returning the value? Use action!
Available
The action <T1, T2, T3, T4> delegate transmits methods as parameters without explicitly declaring custom delegates. The encapsulated method must correspond to the method signature defined by the delegate. That is to say, the encapsulated method must have four parameters that are passed to it through values and cannot return values. (In C #, this method must return void. In Visual Basic, sub... End sub structure to define it .) Generally, this method is used to execute an operation.
The usage is similar to func!
Msdn: http://msdn.microsoft.com/zh-cn/library/bb548654 (vs.95). aspx
Action: no response or parameter. The usage is as follows:
Action
Action = NULL; // define action
Action = checkisvoid; // The encapsulation method. Only the method name is required.
Action (); // call
Conclusion: The use of func <t, tresult> and action <t>, rather than delegate is to simplifyCodeWith less code to achieve the same effect, we do not need to declare a delegate, the last parameter of func <t, tresult> is always the return type, and
Action <t, tresult> has no return type, but action has no return type or parameter input.
Action <t> generic delegation
Description:
Encapsulate a method that uses only one parameter and does not return a value.
Syntax:
Public Delegate void action <t> (T Arg );
T:
Parameter type: parameter type of the method encapsulated by this delegate
Arg:
Parameter: parameters of the method encapsulated by this delegate
Note:
With this delegate, the method can be passed as a parameter.
Other forms:
Public
Delegate void action <t1, T2> (T1 arg1, T2 arg2 );
Public Delegate
Void action <T1, T2, T3> (T1 arg1, T2 arg2, T3 arg3 );
Public Delegate
Void action <T1, T2, T3, T4> (T1 arg1, T2 arg2, T3 arg3, T4
Arg4 );
Example:
Protected void page_load (Object sender, eventargs
E)
{
List <int> List = new
List <int> ();
List. addrange (New int [] {7, 6, 10, 1, 2, 3, 4, 5,
8 });
Action <int> action = new
Action <int> (addfive );
List. foreach (action );
// Same effect
// Action <int>
Action = new
Action <int> (addfive );
// List. foreach (action );
// List. foreach (x
=> Response. Write (x + 5). tostring () +
"<Br/> "));
// Same effect
// Action <int>
Action = new
Action <int> (addfive );
// List. foreach (action );
// List. foreach (delegate (int
I)
//{
// Httpcontext. Current. response. Write (I +
5). tostring () + "<br/> ");
//});
}
Public
Static void addfive (int
I)
{
Httpcontext. Current. response. Write (I + 5). tostring () +
"<Br/> ");
}
Result:
12
11
15
6
7
8
9
10
13
Action <(
<(T>)> delegate (msdn)
Posted on jowo read (128) Comment (0) Edit
Favorites
Note: encapsulate a method that uses only one parameter and does not return a value.
Namespace: System
ProgramSet: mscorlib (in
Mscorlib. dll)
C #
Public Delegate void action <t> (
T
OBJ
)
Type parameter
T
The parameter type of the method encapsulated by this delegate.
Parameters
OBJ
Type: T
Parameters of the method encapsulated by this delegate.
Remarks
You can use this delegate to pass methods as parameters without explicitly declaring custom delegates. 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 cannot return a value. (In
In C #, this method must return void. In Visual Basic, sub... End sub structure to define it .)
Generally, this method is used to execute an operation.
018hxwa8.alert_note(zh-cn,vs.902.16.gif description:
To reference a method that has a parameter and returns a value, use the generic
Func <(of <(T, tresult>) delegate.
When using action <(
<(T>) You do not need to explicitly define a delegate for a method that encapsulates only one parameter. For example, the following code explicitly declares
And the writeline method or showwindowsmessage
Method reference is assigned to its delegated instance.
C #
Copy code
Using system;
Using
System. Windows. forms;
Delegate void displaymessage (string
Message );
Public class testcustomdelegate
{
Public static void
Main ()
{
Displaymessage messagetarget;
If
(Environment. getcommandlineargs (). length> 1)
Messagetarget =
Showwindowsmessage;
Else
Messagetarget =
Console. writeline;
Messagetarget ("Hello, world! ");
}
Private Static void showwindowsmessage (string message)
{
MessageBox. Show (Message );
}
}
The following example simplifies the code by instantiating action <(of <(T>)
Instead of explicitly defining a new delegate and assigning the naming method to the delegate.
C #
Copy code
Using system;
Using
System. Windows. forms;
Public class testaction1
{
Public static
Void main ()
{
Action <string> messagetarget;
If (environment. getcommandlineargs (). length> 1)
Messagetarget = showwindowsmessage;
Else
Messagetarget =
Console. writeline;
Messagetarget ("Hello, world! ");
}
Private Static void showwindowsmessage (string message)
{
MessageBox. Show (Message );
}
}
You can also
C # Use action <(of <(T>)> together with the anonymous method. (For an introduction to anonymous methods, see anonymous methods (C #
Programming Guide ).)
C #
Copy code
Using system;
Using
System. Windows. forms;
Public class testanonmethod
{
Public
Static void main ()
{
Action <string> messagetarget;
If (environment. getcommandlineargs (). length> 1)
Messagetarget = delegate (string s) {showwindowsmessage (s );
};
Else
Messagetarget = delegate (string s ){
Console. writeline (s );};
Messagetarget ("Hello, world! ");
}
Private Static void showwindowsmessage (string message)
{
MessageBox. Show (Message );
}
}
You can also set
Lambda expressions are assigned to the action <(of <(T>)> delegate instance. (For an introduction to lambda expressions, see Lambda
Expression (C # programming guide ).)
C #
Copy code
Using system;
Using
System. Windows. forms;
Public class testlambdaexpression
{
Public
Static void main ()
{
Action <string> messagetarget;
If (environment. getcommandlineargs (). length> 1)
Messagetarget = s => showwindowsmessage (s );
Else
Messagetarget = s => console. writeline (s );
Messagetarget ("hello,
World! ");
}
Private Static void showwindowsmessage (string
Message)
{
MessageBox. Show (Message );
}
}
018hxwa8.alert_note(zh-cn,vs.902.16.gif description:
Visual Basic Requirements
Lambda expression return value. Therefore, you cannot delegate action <(of <(T>)> to Lambda in Visual Basic.
Expression.
Both foreach and foreach <(of <(T>) Use action <(
<(T>) delegate as a parameter. You can perform operations on each element in an array or list by using the delegate encapsulation method. This example uses foreach
Method description.
Example
The following example shows how to use the action <(of <(T>) delegate to print
List <(of <(T>) object content. In this example, the content of the list is displayed on the console using the print method. In addition, C #
The example also shows how to use an anonymous method to display the content to the console.
C #
Copy code
Using system;
Using
System. Collections. Generic;
Class Program
{
Static void
Main ()
{
List <string> names = new
List <string> ();
Names. Add ("Bruce ");
Names. Add ("Alfred ");
Names. Add ("Tim ");
Names. Add ("Richard ");
//
Display the contents of the list using the print
Method.
Names. foreach (print );
// The following
Demonstrates the anonymous method feature of C #
// To display
Contents of the list to the console.
Names. foreach (delegate (string
Name)
{
Console. writeline (name );
});
}
Private
Static void print (string
S)
{
Console. writeline (s );
}
}
/* This code will
Produce output similar to the following:
* Bruce
* Alfred
* Tim
*
Richard
* Bruce
* Alfred
* Tim
* Richard
Http://www.cnblogs.com/zjw2004112/archive/2009/09/30/csharp-action-t.html
C # features-anonymous methods and lambda expressions
In our programs, we often have the following requirements:
1.
A temporary method is required. This method is only used once, or is rarely used.
2.
The method body of this method is so short that it is less powerful than the method declaration (I call it a "one-sentence method ").
No way. It is really thankless to write such a method. For example, in some button event processing, some buttons are clicked to bring up a dialog box or call other methods. For example, the following code:
This. btnrefresh. Click
+ = New system. eventhandler (this. btnrefresh_click );
Private void
Btnrefresh_click (Object sender, eventargs
E)
{
Binddata ();
}
The "refresh" button is used to call the binddata () data binding method. Therefore, we have to write a new method. Okay, C #
2.0 provides an anonymous method for us:
This. btnrefresh. Click + = delegate (Object sender, eventargs E)
{Binddata ();
};
The boring code is gone. Do you want to know the behind-the-scenes hacker?
In fact, the compiler is still working on the next thing: it creates a new method for us, it just saves us code on the surface.
Privatevoidb _ 0 (Object
Sender, eventargs
E)
{
This. binddata ();
}
Let's take a look at the name of the method generated by the compiler:
B _0, test is the place where the anonymous method is placed (because I put the button time in a test method)
Note that if the anonymous method is used in the instance method, the method generated by the compiler for us is also an instance method. Otherwise, it is a static method.
Do you think that the anonymous method is very good, which reduces a lot of code? But the use of anonymous methods is still not human-oriented. What is human-oriented? For example, you can read the program code in a natural language,
In this way, it is humane. In. net
In 2.0, the system. Collections. Generic namespace contains some new methods in the list. For example, find. How can we call an anonymous method:
Books. Find (delegate (Book
Book) {return book. Price <
50 ;});
The code is very simple, but it cannot be read out. Let's take a look at the lambda expression syntax:
Books. Find (Book => book. Price <50); this Lambda expression can be read as follows: give you a book and return true if its price is less than 50.
Well, let's go into the lambda expression:
After the Assembly with Lambda expressions is decompiled, we find that it is actually no different from the anonymous method. Lambda's input parameters correspond to the parameters in the delegate brackets. Since lambda expressions can infer the parameter type, the parameters here do not need to be declared.
Lambda operators read as "goes
To ", followed by the expression or statement block (this is also different from the anonymous method, the anonymous method can only use the statement block but not the expression ), the following example shows the types of lambda expressions:
// The type of X is omitted. the compiler can deduce it based on the context, followed by an expression.
// The type of X is omitted. the compiler can deduce it based on the context, followed by an expression.
X
=> X + 1
Deleage (int x) {return x + 1 ;}
// The block is followed by the statement Block
X => {return
X + 1 ;}
Delegate (int x) {return x + 1 ;}
// The input parameter can also contain the type. Do not forget the parentheses after the type.
(Int x)
=> X + 1
Delegate (int x) {return x + 1 ;}
// You can also enter multiple parameters separated by commas (,). Do not forget parentheses.
(X, y)
=> X + Y
Delegate (int x, int y) {return X + Y ;}
// No parameters are returned.
() =>
1
Delegate () {return
1 ;}
This is the way lambda expressions are used, but there are many stories and mysteries behind lambda. Lambda expressions can be used to construct an Expression Tree, and the expression tree is as important as a tree root for the LINQ clause. We will not discuss the expression tree here. This is not something that can be clearly stated in a few words. We will discuss it further when the time is ripe.
Read more about lambda expressions
Lambda actually has a long history. The machines we use today are from the Von noriman system and belong to the Turing Machine. Before that, there was also a theory called the lambda algorithm, however, since the Turing machine was first implemented, it became quite popular. The Lambda algorithm later became a functional programming language , especially lisp, in functional programming languages, functions are the first element. function parameters return values are all functions. programs have no variables and function nesting functions. Functional programming languages have always existed in the ivory tower, so they are not widely used in the industry. However, in recent years, the industry prefers the "Retro" style, therefore, functional programming languages are slowly taking the stage of history. Functional programming can solve some imperative Programming Problems (or it is very troublesome to solve ). C # What should I do with function-style programming? The method defined by the original method is definitely not feasible. 2.0 of anonymous methods solve this problem in a program, but it is still not enough, lambda in 3.0 has finally been well solved. A Lambda is a
delegate, and a delegate points to a method. Now we can simply pass the method as a parameter using lambda, layers can also be nested, which is very simple.