From the university began to do the C # this piece, also do C # for several years, and recently from iOS back to. NET, continue to do C #, before the habit of blogging, blogging is also from the time I do iOS, and now that since the. NET, then write something about. NET blog, it may be in Daniel's eyes these are simple basis, but look back to see I was a beginner when I thought entrusted events is not easy to understand, I am also here to contact OC, the two have a comparative study. After all, they are object-oriented languages, and ideas are interlinked.
The delegate, like block in OC, points to a function that is not similar to a C + + function pointer. But the delegate is not the same as the function pointer, the delegate is completely object-oriented, and the type is safe and reliable. The pointer to C + + simply points to the member function, while the delegate encapsulates an object instance and method.
A delegate declaration is used to define a class that derives from the System.Delegate class.
Format: Property set modifier delegate return value type (A) identifier (C) (parameter list (B));
First, what is entrusted?
Look at the Scarlet letter above we can understand the fact that the delegate is a class. What is a class, actually? A class is also a data type, which, like the string class, is also a data type, so the delegate is actually a data type, but this data type is a little different from the other, and it's a data type that points to a function. A function named identifier C with a return value of a and a formal parameter list of B. In fact, this is similar to the block in OC, which is also used to define functions in block. We use typedef void (^MYBLOCK1) (int a,int b) to define a block, which is actually defining a data type. The above delegate declaration is also a data type that defines a reference type.
Second, how to use the Commission?
It also says that declaring a delegate is actually declaring a data type, which is the same as a person, a string. We are using delegates and using the person, string type of data. It is also declared first: the public type (person, String) variable (or property) name. So that's what we do when we use a delegate. Just this variable or attribute corresponds to a function.
Iii. examples
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedelegate{//defines a class derived from the System.Delegate class//It can also be understood as a data type that points to a function with a return value of void parameter as a person object//We can also interpret the person class as a data type except that it contains the name and age Public Delegate voidEatfood (person P); Public classPerson { Public stringName {Get;Set; } Public intAge {Get;Set; } PublicPerson (stringNameintAge ) {Name=name; Age=Age ; } //since a delegate is a data type and a string, you can declare a proxy variable as if you were declaring a string object PublicEatfood Eatfood; Public voideating () {if(Eatfood! =NULL) {Eatfood ( This); } } }}
The above defines a person class, which defines a class eatfood that derives from the System.Delegate class, while declaring a variable of the Eatfood class type in the person class, in the eating () This variable is used in the function. PS: Please note the comments in the above code . In the following code, we define two person objects, one Chineseperson one Englishperson, and the Eatfood variables of two classes, respectively, to specify different functions.
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedelegate{classProgram {Static voidMain (string[] args) {Person Chineseperson=NewPerson ("Xiao Ming", -); //instantiating an object from a constructor functionChineseperson.eatfood =NewEatfood (chineseeat); Chineseperson.eating (); Console.WriteLine ("--------------------------------------"); Person Englishperson=NewPerson ("Ivan", -); //instantiating an object by direct replicationEnglishperson.eatfood =englisheat; Englishperson.eating (); Console.ReadLine (); } Static voidchineseeat (Person p) {Console.WriteLine ("I am {0}, I am {1} years old this year, I eat steamed bread", P.name,p.age); } Static voidenglisheat (Person p) {Console.WriteLine ("i ' m {0},i am {1}, I eat Mianbao", P.name,p.age); } }}
You can see that specifying different Eatfood variables for different objects does not perform the same result.
Iv. differences between delegates and other data types
It also says that you can treat a delegate as a data type, but it differs from the normal data type. This may be the present personality, the Commission also has a delegated personality.
The delegate instantiation is used to create the delegate instance, and the class instance creation syntax is the same. But delegates can encapsulate multiple methods, and the collection of these methods is called the invocation list. The delegate uses the +, + = 、-、-= operator to add or remove methods to the invocation list.
We have changed the above code slightly, the person class does not change, only change the main method.
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedelegate{classProgram {Static voidMain (string[] args) {Person Chineseperson=NewPerson ("Xiao Ming", -); //instantiating an object from a constructor functionChineseperson.eatfood =NewEatfood (chineseeat); Chineseperson.eatfood+=englisheat; Chineseperson.eating (); Console.WriteLine ("--------------------------------------"); Person Englishperson=NewPerson ("Ivan", -); //instantiating an object by direct replicationEnglishperson.eatfood =englisheat; Englishperson.eatfood+=chineseeat; Englishperson.eating (); Console.ReadLine (); } Static voidchineseeat (Person p) {Console.WriteLine ("I am {0}, I am {1} years old this year, I eat steamed bread", P.name,p.age); } Static voidenglisheat (Person p) {Console.WriteLine ("i ' m {0},i am {1}, I eat Mianbao", P.name,p.age); } }}
In order to promote the exchange between China and the West, many people go to study abroad also have a lot of come to the Chinese, so in the aspect of eating each other will eat each other. So you have to add a way to show that you eat different foods. With a delegate you can add and delete the invocation list by using + = and-=, which is a lot more. As you can see from the output below, each person object invokes the Chineseeat, Englisheat function.
V. Benefits
The demo above also shows how the delegate is used, and we can think about the benefits of using it using the above. If we do not use a delegate to achieve this function, we may be in the person class to make a judgment, judge whether it is chinses or Chinese, but so, if the day has Japan, France, and so on, then more than a good number of judgments. Scalability is not good. It may be said that you can define a virtual method in person, the declaration of Chinese, English class inherits the person class override virtual method, this is really a method, if there is a new extension can be directly create a new class override virtual method is done, However, if this method is only different, it is necessary to write a class, which is overkill. So the delegation is still a good choice. This is even more problematic if you want to add more to the language. Having entrusted these all to resolve.
VI. Events
The interaction between objects is achieved through message delivery, and events are messages sent by the object, which notifies the operation of the occurrence by signaling. The object that raises the event is the event sender, and the object that captures the event and responds to it is the event receiver. In event communication, the event sender does not know which object or method will receive the event it raises, and what is needed is a link between the sender and the receiver, using the delegate in C # as the link.
Event declaration format: Property Set modifier event delegate type events name.
The truth is that the event is the encapsulation of the delegate variable. Notice what I've written all along is a variable of the delegate type, one of the three main object-oriented features is encapsulation, such as variables and attributes. Using a delegate directly above to specify a function is the same as using a variable directly, but in an object-oriented way, the variable is generally not directly accessed, but the variable is encapsulated, for example, the property {Get;set;} Method. An event is an encapsulation of a delegate. Let's take a look at the use of events, as we did with delegates above, we declare an event in the person class.
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedelegate{//defines a class derived from the System.Delegate class//It can also be understood as a data type that points to a function with a return value of void parameter as a person object//We can also interpret the person class as a data type except that it contains the name and age Public Delegate voideatfooddelegate (person P); Public classPerson { Public stringName {Get;Set; } Public intAge {Get;Set; } PublicPerson (stringNameintAge ) {Name=name; Age=Age ; } //since a delegate is a data type and a string, you can declare a proxy variable as if you were declaring a string object//Public Eatfood Eatfood; //prior to declaring the delegate directly, it is now declaring an event Public Eventeatfooddelegate Eatfoodeventhandler; Public voideating () {if(Eatfoodeventhandler! =NULL) {Eatfoodeventhandler ( This); } } }}
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedelegate{classProgram {Static voidMain (string[] args) {Person Chineseperson=NewPerson ("Xiao Ming", -); //instantiating an object from a constructor functionChineseperson.eatfoodeventhandler + =Neweatfooddelegate (chineseeat); Chineseperson.eatfoodeventhandler+=englisheat; Chineseperson.eating (); Console.WriteLine ("--------------------------------------"); Person Englishperson=NewPerson ("Ivan", -); //you can use = directly in the delegate to copy the delegate object and cannot be used directly in the event = To use + =Englishperson.eatfoodeventhandler + =Neweatfooddelegate (englisheat); Englishperson.eatfoodeventhandler+=chineseeat; Englishperson.eating (); Console.ReadLine (); } Static voidchineseeat (Person p) {Console.WriteLine ("I am {0}, I am {1} years old this year, I eat steamed bread", P.name,p.age); } Static voidenglisheat (Person p) {Console.WriteLine ("i ' m {0},i am {1}, I eat Mianbao", P.name,p.age); } }}
As you can see, events are used to achieve the same functionality.
Seven, the difference between the entrustment and the agency design pattern
Whether you use delegates or events, they all call the methods in the B object in the A object (the person object in this case), which is similar to the design pattern. The specific proxy design pattern is omitted here, both the delegate and the proxy are the methods in the A object using the B object. However, they are still different, the delegate in a directly using the method in B, is between the class and method, the proxy design pattern is to set a class B variables, and then B to use the method in B, is between the class and the class. This is also my personal understanding, do not know right, wrong words also hope Daniel Correct, lest delay other socialist successor.
C # syntax delegates and events