- Delegate: A reference type that can be used to define a method signature, thereby passing a method as a parameter to another method using a delegate implementation. Similar to the contention of a function in C + +, a delegate enables a programmer to encapsulate a method reference within a delegate object .
- To define and declare a delegate:
1 Delegate return value delegate name (parameter list); 2 eg: 3 Public Delegate void Sayhellodelegate (string name);
- Use delegates: Delegates actually define methods and signatures by return values and parameter lists. Any method that has the same return value and a parameter list (signature) as the delegate can be assigned to the delegate.
1 Public Delegate voidSayhellodelegate (stringname);//declaring a delegate2 PublicViod Sayhelloenglish (stringName//declaring Methods3 {4Console.WriteLine ("hello,{0}", name);5 }6Sayhellodelegate S=sayhelloenglish;//assigning a method to a delegate objectView CodeSeveral forms of delegate instantiation:
1 1. Using the New keyword2Sayhellodelegate s=Newsayhellodelegate (sayhelloenglish);3 2. Direct Assignment4Sayhellodelegate s=Sayhelloenglish;5 3. Using anonymous Methods6Sayhellodelegate s=Delegate(stringname)7 {8Console.WriteLine ("hello,{0}", name);9 }Ten 4. Use a lambda expression, for example: OneSayhellodelegate s=name=> A { -Console.WriteLine ("hello,{0}", name); -}1 after the delegate is instantiated, the delegate can be called as if it were called a method. Eg:2 s ("John");
- Multicast delegate: A delegate object can contain multiple methods. When a multicast delegate is called, each method is executed one time in the order of assignment.
- Using the operator + implementation: A useful property of a delegate object, you can use the + operator to assign multiple objects to a delegate instance. Here the operator + operand can only be a delegate object, and the method cannot be signed.
1 Public Delegate voidSayhellodelegate (stringname);2 Public voidSayhelloenglish (stringname)3 {4Console.WriteLine ("hello,{0}", name);5 }6 Public voidSayhellochinese (stringname);7 {8Console.WriteLine ("hello, {0}", name);9 }TenSayhellodelegate s1=Newsayhellodelegate (sayhelloenglish); OneSayhellodelegate s2=Sayhellochinese; ASayhellodelegate s3=s1+s2;//only delegate object on both sides of the operatorView Code
- Using the operator + =
1 Public Delegate voidSayhellodelegate (stringname);2 Public voidSayhelloenglish (stringname)3 {4Console.WriteLine ("hello,{0}", name);5 }6 Public voidSayhellochinese (stringname);7 {8Console.WriteLine ("hello, {0}", name);9 }TenSayhellodelegate s=Newsayhellodelegate (sayhelloenglish); OneSayhellodelegate S+=sayhellochinese;//the Action object on the right is the method signatureView Code
C # Learning Notes 03--delegates and events