Basic understanding of delegation
1. What is delegation?
1.1 delegation is a reference type. This type is suitable for encapsulating methods with specific signatures. We can understand delegation as a special type that encapsulates function pointers and methods.
1.2 Using delegation we can encapsulate the method in the delegate, and then call the delegate to call the method in it.
2. Basic declaration format of delegation
Modifier delegate return type delegate name (parameter list) -- return type and parameter list must be consistent with Method
3. How to understand Delegation
3.1 we can regard the delegate as a box, and the return type and parameter list as constraints for putting items in the box,
Think of the method as an item that can be put into the box. When the constraint is satisfied, we can put the method into the box.
4. Basic use rules of delegation
4.1 first, we declare a delegate.
4.2 create a delegated instance
4.3 define a method based on the delegate
4.4 use the delegate call Method
4.5 associate delegation with methods
5. The following code is used to understand the delegation:
5.1 first, we have a class for printing strings.
Class PrintClass
{
// Define a method for printing strings
Public void Print (string str)
{
Console. WriteLine ("str ");
}
}
5.2 now we define a method for printing Hello in the class, but we don't want to print the action in ourselves. We want to give the action to PrintClass for printing.
Now we can use the delegate to complete this task.
Class HelloClass
{
Public void PrintHello ()
{
}
}
5.2.1 first, we declare a delegate outside the class
Public delegate void PrintHandler (string str );
5.2.2 create a delegate instance in the HelloClass class
Public PrintHandler PrintHandle;
5.2.3 because we already have a method, skip this step and create a method without it.
5.2.4 we call the delegate Activation Method in PrintHello
// Print Hello
Public void PrintHello ()
{
// Check whether the delegate can be called.
If (PrintHandle! = Null)
{
// 5. Activate the delegate
PrintHandle. Invoke ("Hello ");
}
}
5.2.5 now we have prepared to associate the delegate with the method. When PrintHello () in HelloClass is called, it will call Ptint () in PrintClass ()
Static void Main (string [] args)
{
PrintClass Pc = new PrintClass ();
HelloClass Hc = new HelloClass ();
// 4. Associate delegation with methods
Hc. PrintHandle = Pc. Print;
Hc. PrintHello ();
}
6. Finally, I hope to help you have a basic understanding of delegation.