Understanding delegate Types

Source: Internet
Author: User
Tags mscorlib

Afraid of everyone to see the mess do not know what to say, the first sentence described under: As the title, in C # delegate is a type, such as class also need to declare, define, assign, and with class at the same level
before introducing the definition of the relevant content (I am not a literal, personally think, some things must not understand the definition, can not be vague, otherwise it will only be indefinitely)
delegate : (keyword-type, reference type [Class,interface, etc. these are reference type keywords])

Delegate is a reference type that can be used to encapsulate named or anonymous methods. (Not all reference types are Class)

is a type that defines a method signature and can be associated with any method that has a compatible signature.

Any method in the accessible class or struct that matches the signature of the delegate (consisting of the return type and parameters) can be assigned to the delegate.

event: (keyword, modifier [Readonly,static,unsafe, etc. these are modifier keywords])
                    The event keyword is used to declare events in the Publisher class.  (therefore, the event-modified multicast delegate [MulticastDelegate] is called "Events" [this event is not              a key-word event, but a special instance of MulticastDelegate])
Delegate (Class-I under the System namespace [assembly mscorlib])
                 
MulticastDelegate(Class-I under the System namespace [assembly mscorlib])
                 

EventHandler(delegate [He is not a class, is a delegate])

is actually a kind of. NET is the predefined delegate type for us, which will be followed by the

now, let's see what's Inside delegate .Can clearly see that delegate is really a class, and directly inherit from the object (this inheritance is Il level, C # level is not visible so do not care too much) there are many methods, but we may be able to use only public methods, And this is an abstract class we can not directly instantiate (the same is also) to see what multicastdelegate inside is obvious multicastdelegate is also a class and direct inheritance with the above delegate more than 2 private fields _ Invocationcount, _invocationlist, and some new ways to see this multicastdelegate, and delegate, although the name is very confusing, but they are not commissioned, is class (The relationship between this class and our delegate is mentioned below), and normally we don't use it, but often people confuse delegate with delegate (not exactly a thing, unlike string,string) you can see what's inside of EventHandler .


You can see that there is a declaration of a delegate (which is similar to declaring a class), that he declares a delegate type of data, so EventHandler is clear that it is a delegate type of data (just a declaration, And delegate's statement can be placed on the top level of the namespace with other data structure of the Declaration to enjoy the consent of the treatment (but the IL code is still decorated with class, I personally think that IL is the class is Il class,c# inside the class is C # class, is not the same thing. Not because the IL is in the class to modify the wishful thinking that this thing is a class, if so Interface,enum,struck what is also the class, and finally they are 2 of the data, are the same thing)   Now let's look at the whole process of so-called delegates.First step:   We first define/declare a delegate (note is defined) public delegate void Delegateloopchangeeventhandler (object Yourtarget, String YourMessage); Just like this (cannot be defined in an interface or function, but can be defined within a struct) let's see what the CLR does with this sentence   Can be very clear to see that he is really a delegate that briefcase the same small icon is the meaning of the delegate to open it to see what can be seen inside there are 1 public methods, With 3 things that seem to be similar to methods (because of what the 2-box icons mean, I really don't know) there can be methods in the visible delegate (but these methods are not created by ourselves, but when we define the data body of a delegate type, it is a game, And the IDE for us to convert to IL when there is actually a lot of action) we look at this sentence of the code compiler is how to understand, the IDE translated it into what    see it, converted to IL code when there are some things, At IL level it is the class of IL (be sure to distinguish between the class of IL, not the C # syntax) and inherit from MulticastDelegate again stating that this delegateloopchangeeventhandler is a delegate, In IL it behaves as class, and in C # classes, delegates, interfaces are not things of the environment    Second step: We are going to instantiate this delegate (the operation here is similar to  point mypt; FileStream MYFS This is the public static Delegateloopchangeeventhandler onloopchange; I instantiate it in a class, so I can add a modifier (in the test in order to directly use the main function, so we add a static, The actual environment is still recommended to use less static things). Then we can see that the IL code of this sentence is also only one sentence when the program runs here, the value of  onloopchange   is null, that is, we have not initialized/assigned the data of this delegate type   Third step: Let's assign a value  eg 1:  onloopchange = new Delegateloopchangeeventhandler ((x, y) + = {Console.WriteLine ("Myindex" + Myindex++); }); eg 2:  onloopchange + = new Delegateloopchangeeventhandler ((x, y) = {Console.WriteLine ("Myindex" + myindex++) ; }); eg 3:  onloopchange = ((x, y) = = {Console.WriteLine ("Myindex EX");}); EG 4:  onloopchange = new Delegateloopchangeeventhandler (FunTest1);  can see the operation of the assignment has a lot of writing, can be very casual, of course, recommend the last one, You can remove the binding method at any time (not that lambda expression is bad, unless you know that your method is just to do 1, 2 lines of code) This assignment has nothing to say about the same as other types of data assignment, or to look at the CLR's Il (the initialization of a random delegate type, Not with the above)   actually is not very familiar with IL, simply say, whenever we want to assign/initialize he probably first moved the function we want to bind to the stack, And then he created a new delegateloopchange type of data (because we just said that our delegate instance was null after instantiation), and finally replaced our newly null delegate field with this data from the stack.   Again we can onloopchange = ((x, y) = {Console.WriteLine ("Myindex EX");}); This is directly assigned because the IDE will help us to add new Delegateloopchangeeventhandler (...). It's best not to be lazy. Then the assignment of the delegate instance we can use + =, but this + = NULL instance is handled differently for non-null instances if NULL is the initialization process above. If it is not null, the actual operation he is doing is    simply that it adds a method to our instance. (It should be easy to think that the corresponding will have-=). Of course, we can also assign a value at the time of instantiation, that is to say the 2nd step with the first, 3 steps can be done together.
The fourth step: execution of the delegate execution is very simple, just the delegate directly Onloopchange (null,null), the operation is like a call to a method can also be onloopchange. Invoke (null, NULL); In particular, this invoke is not an invoke of the control class in System.Windows.Forms, where he is domainoperationentry, and if the current delegate instance is bound to more than one method, it will be executed individually now by the way. Nvoke of course which thread executes onloopchange,onloopchange on which thread executes, sometimes you might manipulate the UI, when it is not currently the UI thread, what to do, and indeed we can turn off vs UI thread check solve everything, However, this is definitely not recommended, first of all it is difficult to ensure that there is no simultaneous access to the situation, followed by the operation of the UI is generally time-consuming now we can use invoke under control.   The method is also very simple myformcontrol1.invoke (myformcontrol1.mydelegate,new object[] {myString}); That's all you can do (the MSDN I'm picking directly) is simply a control. Invoke (delegate instance): If a parameter is added directly to the following, the instructions below invoke to the UI although the UI thread executes, but the current function waits for the method to return. Use BeginInvoke can solve the last delegate instance run out of how to deal with, generally out of habit will-=, but MSDN did not submit this thing need special destruction or release, should be managed, we do not have to control Okay, let's just say "event ."(In fact, after the delegation, it will not be in the tangled event with the delegation of the relationship) on MSDN has been described very clear and accurate

"Events are special types of multicast delegates that can only be called from the class or struct in which they are declared (the Publisher Class).

So it's clear that the event is a delegate, a delegate that has been modified by a keyword event. (Just like the static int i = 1; Would you say I is not an int data?)

If you have to look for a difference, MSDN says, he just can't call it in another class.

In fact, the event is Microsoft more help us to achieve the write function.

To analyze the exact words he said. "Can only be called from the class or struct in which they are declared (the Publisher Class)"

At first glance is not very simple implementation, the example of this delegate can be modified with private (in fact, vs in the event of the same time the same process)

However, do not forget the function of the delegate, other classes will subscribe to the problem (in fact, the assignment or add the correlation function)

This is not very troublesome, is already private, the other class must not be processed, we are not to write the function alone to expose to the caller to use and so on.

Well, we don't have to deal with it, Microsoft added an event modifier to help us solve

Let's see how Microsoft Does it.

You can see that the special delegate instance of Loopchangeevent is actually decorated with private, but he helped us to add 2 methods internally, with such a so-called event (in fact, 2 static methods are in the event, and do not know why it is displayed in the same sibling), In fact, this event is to open 2 functions for this private delegate instance.

Since the event is a delegate, the use of the method is identical and does not repeat (the only difference is "can only be called from the class or struct that declares them (the Publisher Class)")

It is important to note that the event is immediately decorated, if the current delegate instance to other classes, in other classes can also trigger the delegate (event), but the delegate cannot be directly used as a field of the class to use (trigger)

Now back in front of the EventHandler, it should be clear.

In fact, he is the declaration of the data of the delegate type (the meaning of existence is also just for the convenience of us, or the specification of US)

It's pretty straightforward on MSDN.

[SerializableAttribute] [ComVisibleAttribute (True)]

Public delegate void eventhandler (Object Sender,eventargs e)   This is not the same as the declaration method of the delegate mentioned earlier. So he was commissioned, Microsoft helped us to pre-declare a number of delegates just EventHandler and so on there is an event this word exists, is to remind us that this instance of the delegate type is best to use event to decorate    final summary under   If you want to ask whether the event is a delegate. Then we have to figure out what this is all about. What is the difference between an event and a delegate   or a delegate   These beginnings are explained, not a type of thing, absolutely different. So if you're asking for a delegate instance, then MSDN is very clear about the event instance. The event is a special type of multicast delegate   If the delegate is not a class in C # delegate is absolutely not a class, otherwise you have to delegate this keyword what to do directly with class. But Dclass and delegate were translated into Il when they belong to the Il class. Il is not C # in the end, it does not affect the conclusion: the general application of C # delegate is not class   delegate cross-class message notification across a thread (the execution of a delegate is the class or thread that defines the delegate, the assignment of the delegate is another class or thread, the calling thread is the thread of execution without invoke), This kind of problem is usually added to the event decoration) to pass the delegate to other methods, so that other threads, classes, methods to call (the caller generally only call, the assignment is also done by other modules, which is usually understood as a function pointer)   Things write very messy, can also have a lot of imperfect or wrong place. It seems to be very difficult, forgive me, if there is a mistake, please make a lot of mistakes                                                                                                        References: MSDN,< One-stop sample code base programming Specification> co-editor: None

Understanding delegate Types

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.