Delegate)
A delegate is a reference type used to encapsulate the reference of a method (function. It is similar to the function pointer in C ++, but it is different. The delegate is fully object-oriented and the type is safe and reliable. In addition, the C ++ pointer only points to the member function, the delegate encapsulates object instances and methods at the same time.
Using delegation involves several steps: Delegation declaration, delegation instantiation, and delegation call.
1. Delegation statement
The delegate declaration is used to define a class derived from the system. Delegate class. Its format is:
Type identifier of the attribute set modifier delegate return value (list of parameters );
The modifiers can be public, protected, internal, private, and new.
2. Delegate instantiation
The delegate instantiation is used to create a delegate instantiation. It has the same syntax as the class instance creation. Multiple delegate instances can be encapsulated,
Method. The set of methods is called the call list. The delegate uses the "+", "+ =", "-", and "-=" operators to add or remove methods to or from the call list.
3. Delegated call example
View code
Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Namespace delegate
{
Delegate void timedelegate (string S); // delegate statement
// Create a class
Public class mytime
{
Public static void hellotime (string S)
{
Console. writeline ("Hello {0 }! The time is {1} Now ", S, datetime. Now );
}
Public static void goodbyetime (string S)
{
Console. writeline ("Goodbye {0 }! The time is {1} Now ", S, datetime. Now );
}
Public void sayhello (string S)
{
Console. writeline ("{0 }! The time is {1} Now ", S, datetime. Now );
}
}
Class Program
{
Static void main (string [] ARGs)
{
// Instantiate the delegate, create the delegate instance A, and encapsulate the static method
Timedelegate A = new timedelegate (mytime. hellotime );
Console. writeline ("invoking Delegate :");
// Delegate the call, which is equivalent to the call method mytime. hellotime ("")
A ("");
Timedelegate B = new timedelegate (mytime. goodbyetime );
Console. writeline ("invoking Delegate B :");
B ("B ");
// The delegate instance c encapsulates two methods: hellotime and goodbyetime.
Timedelegate c = A + B;
Console. writeline ("invoking delegate C :");
C ("C ");
C-=;
Console. writeline ("invoking delegate C :");
C ("C ");
Mytime time = new mytime ();
Timedelegate d = new timedelegate (time. sayhello );
Console. writeline ("invoking delegate D :");
D ("D ");
}
}