Commissioned
Delegation is a new object-oriented language feature that has not been seen in the long history of object-oriented languages such as C + +. Microsoft introduced this feature when designing object-oriented languages that run on the. NET Framework platform.
1. Concept:
A delegate can be thought of as a "container" of a function, and it can be used as a function after "loading" a specific function. A delegate variable can be thought of as a type-safe function pointer that can receive only the address of a function that meets its requirements.
2, definition method:delegate keyword. Cases:
int Mydele (int b);
3, using the delegate call function
(1) First define a class, which writes a few methods:
ClassClass1 {Publicint Jiafa (int A,Intb) {Return a +b }Publicint Jianfa (int A, int b) {return a- b; } }
(2) calling a function through a delegate:
Mydele m;Defines a variable m = of an existing delegate typeNew Class1 (). Jiafa;Assign a value to the above variable Console.WriteLine (m (1,2//result is 3m = new Class1 (). JIANFA; Console.WriteLine (M (1,2)); //result is-1
4. Note: A variable of a delegate type can refer to any function that satisfies its requirements.
5, the extension of the delegation:
(1) Special delegate generic set, anonymous delegate
func<Stringstring> MyFunc =new Class1 (). returnstring; // input string, Output Stringconsole.writeline (MyFunc (" Zhang San "));
(2) Direct writing method
func<StringString> Newfunc =DelegateStrings) {return S + "world! "; }; Console.WriteLine (Newfunc ( " John Doe "));
(3) Lambda method simple version 1, replace delegate with s=> (string s)
func<Stringstring> newfunc1 = S=> {return s + "world! ";};
(4) Lambda method simple version 2, two parameters
func<StringStringString> Newfunc2 = (S1,S2) +{ return s1 + "world!" +S2;};
(5) Lambda method simple version 3, remove curly braces, direct write method
func<string,string> newfunc3 = (S1, s2) =>s1+"world!" +S2; Console.ReadLine ();
Object-oriented Fundamentals (vii)