C # Delegate
This blog will share with you the delegation in C.
What is delegation?
Let's first think about this problem. If I want to write a Person class, the definition is as follows:
Public class Person {public string Name {get; set;} public int Age {get; set;} public void ZhuangBi () {// step 1, locate the topic // step 2, find a person who can chat. writeLine ("I am newbility ");}}
In order to make the program more flexible, I don't want to write specific implementations in the ZhuangBi method. The question is, how can we implement the first and second steps? We can abstract an interface and then inject dependencies, but this is not within the scope of this article. Can we add two parameters to the ZhuangBi method? These two parameters point to one method. That is to say, when the method is called, two methods are passed in. One method is responsible for finding the topic, another method is to find the person who can chat. But how can we pass methods as parameters? What is the parameter type?
In the. net world, delegation was born to solve this problem. A delegate is a type that can point to a method. A more accurate definition of a delegate is a type that represents reference to methods with specific parameter lists and return types.
How to define Delegation
To solve the preceding problem, we define a delegate. For simplicity, the parameter list and return values are empty.
public delegate void MyDelegate();
Then modify the ZhuangBi method. The transformed code is as follows:
Public class Person {public string Name {get; set;} public int Age {get; set;} public void ZhuangBi (MyDelegate findTopic, MyDelegate findPerson) {// first, find the topic findTopic (); // then, find the person who can chat, findPerson (); Console. writeLine ("I am newbility ");}}
How to Use Delegation
Finally, we will write another class to call this Person class and pass two methods.
class Program{ static void Main(string[] args) { Person p = new Person(); MyDelegate delegate_FindTopic = FindTopic; MyDelegate delegate_FindPersonToTalk = FindPersonToTalk; p.ZhuangBi(delegate_FindTopic, delegate_FindPersonToTalk); } static void FindTopic() { Console.WriteLine("MongoDB is not too bad"); } static void FindPersonToTalk() { Console.WriteLine("find a geek"); }}
The running result is as follows:
MongoDB is not too badfind a geekI am newbility
Use System-defined delegation
In many cases, we can use the delegate defined by the System. System. Action is the delegate with the parameter list and return values empty. The definition is as follows:
public delegate void Action();
Func <> is a fan-type delegate with 17 heavy loads. up to 16 fan-type parameters can be defined. These two delegates should be able to meet almost all application scenarios.