Delegate is a type of secure encapsulation method, which is similar to function pointers in C and C ++. Unlike function pointers in C, delegation is object-oriented, type-safe, and insurance. The delegate type is defined by the delegate name. The following example declaresDelCan encapsulate a method that uses a string as a parameter and returns a void.
public delegate void Del(string message);
When constructing a delegate object, the name of the Delegate-wrapped method is usually provided or the anonymous method is used. After the delegate is instantiated, the Delegate will pass the method calls to it to the method. The parameters passed by the caller to the delegate are passed to the method. The return values (if any) from the method are returned by the delegate to the caller. This is called a call delegate. An instantiated delegate can be called as the wrapped method itself. For example:
// Create a method for a delegate.public static void DelegateMethod(string message){ System.Console.WriteLine(message);}
This example shows how to combine multicast delegates. One purpose of the delegate object is that it can be used+Operators assign them to a delegated instance to be a multicast delegate. The combination of the two delegates can be called. Only delegates of the same type can be combined.
-The operator can be used to remove a component delegate from the delegate of a combination.
Class class1 {Public Delegate void printdelegate (string name, string ID); Public Delegate void del (int I); static void main (string [] ARGs) {class1 OBJ = new class1 (); printdelegate delegate1 = printstudent; printdelegate delegate2 = obj. printebook; // + the object operated by the operator can only be a delegate object. // Printdelegate multidel = delegate1 + delegate2; // But + = the operation object on the right can be a method signature. // Simple multicast delegation. Printdelegate multidel = NULL; multidel + = obj. printebook; multidel + = printstudent; multidel ("test", "123"); del d = delegate (int I) {console. writeline (++ I) ;}; D (10); console. read ();}/*** both static and non-static methods can be used for delegation and signature methods. ** // Static method public static void printstudent (string name, string ID) {console. writeline ("student information"); console. writeline ("student ID: {0}", ID); console. writeline ("Name: {0}", name) ;}// non-static method. Public void printebook (string bookname, string code) {console. writeline ("books"); console. writeline ("No.:" + code); console. writeline ("name:" + bookname );}}