PanPen120 on CSDN original, such as other sites reproduced please pay attention to the layout and the source:
Research commissioned, because there is the basis of function pointers, but also easy to get started, but for some concepts and practices, always to make it very clear and tangled, these several commissioned articles I was combined with the "C # and. NET4 Advanced Program Design", MSDN, draw on other people's blog summary discourse, With the most direct and concise words to clarify
Key words:
Func Action Delegate Three kinds
Generally speaking generics are Func and action, which is a shorthand for delegates
I will also join the delegate of this genuine delegate because he can also write generics
Describe:
The number of arguments to a fixed delegate, but the type of the parameter is dynamically variable
Purpose \ Advantage:
Steps to define a delegate type are omitted
Difference between action and fun:
Action has no return value, the action overload has a number of 1-4 arguments
Func has a return value. The Func overloads have a number of 1-4 parameters
Action Example:
namespace testaction{ class program { //public delegate void Action<t> (T arg); //Note This line is the prototype of the action, which can be written without writing, that is, the purpose mentioned above ... this line of the//note is the prototype of the action, which shows that the action has no return value Static voidMain (string[] args) {action<int> action = printfmyage; Action4); action<string> Action2 = printfmyname; Action2 ("PanPen120"); Console.ReadLine (); }Static voidPrintfmyage (intMyAge) {Console.WriteLine ("My age is {0}", MyAge); }Static voidPrintfmyname (stringMyName) {Console.WriteLine ("My Name is {0}", myName); } }}
Func Example:
//The difference is that the delegate registration function has a return value namespace testaction{ class program { Static voidMain (string[] args) {func<int,int> action = printfmyage; Action4); func<string,int> Action2 = printfmyname; Action2 ("PanPen120"); Console.ReadLine (); }Static intPrintfmyage (intMyAge) {Console.WriteLine ("My age is {0}", MyAge);return 1; }Static intPrintfmyname (stringMyName) {Console.WriteLine ("My Name is {0}", myName);return 1; } }}
Delegate Example:
Namespace genericdelegate{ Public Delegate voidMygenericdelegate<t> (T Arg); Class Program {Static voidMain (string[] args) {mygenericdelegate<string> strtarget =Newmygenericdelegate<string> (stringtarget); Stringtarget ("Some string Data"); mygenericdelegate<int> inttarget =Newmygenericdelegate<int> (inttarget); Inttarget (9); Console.ReadLine (); }Static voidStringtarget (stringARG) {Console.WriteLine ("Arg in uppercase is: {0}", Arg. ToUpper ()); }Static voidInttarget (intARG) {Console.WriteLine ("++arg is: {0}", ++arg); } }}
Note:
If you use a generic delegate, you can use action or func, there is no need to have a simple and delegate this way
C # delegate three-generic delegate