Decryption of events

Source: Internet
Author: User
Tags reflector

In the previous article wrote the delegation, also said that the delegation is the C # many characteristics of the foundation, this is to tell the event is based on the trust. In c#1.0, delegates and events are the most important of the two properties.

1. What is an event?

Events are designed into two types of roles-event publishers and event subscribers. When an event occurs, the event Publisher publishes the message, and the event Subscriber receives the information and handles it accordingly, which is the process of the event.

2. Usage Events

2.1 Defining events

Defining events in C # and defining the members of a class is very similar, as long as an event keyword is available. Like what:

public event EventHandler Birthday;

Where event is a keyword, and EventHandler is a delegate type.

Therefore, the structure of the event definition can be summarized as: The Access Modifier event delegate type events name, where the delegate type can be a custom delegate type, or it can be. The predefined delegate type EventHandler in the Net class library.

2.2 Subscribing and canceling events

Event subscribers need to subscribe to event messages published by the event Publisher to receive messages and handle them when the event is triggered. In C #, you can subscribe to events by using "+ =" and use "-=" to unsubscribe from events.

public class Bridegroom
{
Custom delegate
public delegate void Marryhandler (string msg);
Define an event with a custom delegate type with the event name Marryevent
public event Marryhandler Marryevent;

Issue Events
public void Onmarriagecoming (String msg)
{
Determine if an event-handling method is bound
if (marryevent!=null)
{
Triggering events
Marryevent (msg);
}
}


static void Main (string[] msg)
{
Bridegroom Bridegroom=new bridegroom ();

Instantiating a Friend object
Friend Friend1=new Friend ("Zhang San");
Friend Friend2=new Friend ("John Doe");
Friend Friend3=new friend ("Harry");

Subscribe to Events using "+ ="
Bridegroom. Marryevent+=new Marryhandler (friend1. SendMessage);
Bridgeroom. Marryevent+=new Marryhandler (Friend2. SendMessage);

Notifies when only the object subscribed to the event is notified
Bridegroom. Onmarriagecoming ("Friend,i would marry!!");
Console.WriteLine ("------------------------------------");

Use "-=" to cancel an event subscription, at which point John Doe will not receive notifications
Bridegroom. Marryevent-=new Marryhandler (Friend2. SendMessage);

Bridegroom. Marryevent+=new Marryhandler (Friend3. SendMessage);

Bridegroom. Onmarriagecoming ("Friend,i would marry!!");

Console.readkey ();
}
}

public class Friend
{
public string Name;
Public Friend (string name)
{
Name=name;
}
event handler, which needs to conform to the definition of the Marryhandler delegate
public void SendMessage (String message)
{
Console.WriteLine (message);
Console.WriteLine (this. Name+ "received, then on time to participate");
}
}

It is important to note that the definition of an event handler needs to be consistent with a custom delegate definition, that is, the number of arguments, the type of the parameter, and the return type, and so on.

In addition to using custom delegate types to define events, you can also use the. NET class library, the predefined delegate types EventHandler to define events and need to be aware of their arguments.

public class Bridegroom
{
Use. NET class Library, event named Marryevent
Public event EventHandler Marryevent;

Issue Events
public void Onmarriagecoming (String msg)
{
Determine if an event-handling method is bound
if (marryevent!=null)
{
Console.WriteLine (msg);
Triggering events
Marryevent (This,new EventArgs ());
}
}


static void Main (string[] msg)
{
Bridegroom Bridegroom=new bridegroom ();

Instantiating a Friend object
Friend Friend1=new Friend ("Zhang San");
Friend Friend2=new Friend ("John Doe");
Friend Friend3=new friend ("Harry");

Subscribe to Events using "+ ="
Bridegroom. Marryevent+=new Marryhandler (friend1. SendMessage);
Bridgeroom. Marryevent+=new Marryhandler (Friend2. SendMessage);

Notifies when only the object subscribed to the event is notified
Bridegroom. Onmarriagecoming ("Friend,i would marry!!");
Console.WriteLine ("------------------------------------");

Use "-=" to cancel an event subscription, at which point John Doe will not receive notifications
Bridegroom. Marryevent-=new Marryhandler (Friend2. SendMessage);

Bridegroom. Marryevent+=new Marryhandler (Friend3. SendMessage);

Bridegroom. Onmarriagecoming ("Friend,i would marry!!");

Console.readkey ();
}
}

public class Friend
{
public string Name;
Public Friend (string name)
{
Name=name;
}
event handler, which needs to conform to the definition of the Marryhandler delegate
public void SendMessage (object S,eventargs e)
{
Console.WriteLine (this. Name+ "received, then on time to participate");
}
}

EventHandler is a predefined delegate type in the. NET class library that handles events that do not contain event data. Use reflector to view the specific definition of EventHandler:

[Serializable, ComVisible (true), __dynamicallyinvokable]  Public Delegate EventHandler e);

As you can see from the definition, the return type of the delegate type is void, the first parameter sender is responsible for saving the reference to the triggering event object, the type is object, and the second argument E is responsible for saving the event data. The EventArgs class is also a class defined in the. NET class library, and it does not hold any data, and if you want to include event data in the event, you must use the derived class of EventArgs.

2.3 Extending the EventArgs class

It says that if you want to include event data in an event, you must use a derived class of EventArgs. The specific implementation code is as follows:

public class Marryeventargs:eventargs
{
public string Message;
Public Marryeventargs (String msg)
{
message=msg;
}
}

public class Bridegroom
{
Custom delegate type, delegate contains two parameters
public delegate void Marryhandler (object Sender,marryeventargs e);
Define an event with a custom delegate type with the event name Marryevent
public event Marryhandler Marryevent;
Issue Events
public void Onmarriagecoming (String msg)
{
Determine if an event-handling method is bound
if (marryevent!=null)
{
Triggering events
      Marryevent (this,new Marryeventargs (msg));
}
}


static void Main (string[] msg)
{
Bridegroom bridegroom=new bridegroom ();     
//Instantiate friend object
friend Friend1=new friend ("Zhang San");
Friend Friend2=new Friend ("John Doe");
Friend Friend3=new friend ("Harry");
//use "+ =" to subscribe to events
Bridegroom. Marryevent+=new Marryhandler (friend1. SendMessage);
Bridgeroom. Marryevent+=new Marryhandler (Friend2. SendMessage);
//Notifies you that only the object subscribed to the event can receive notification
bridegroom. Onmarriagecoming ("Friend,i would marry!!");
Console.WriteLine ("------------------------------------");
//use "-=" to cancel the event subscription, at which point John Doe will not receive the notification
bridegroom. Marryevent-=new Marryhandler (Friend2. SendMessage);
Bridegroom. Marryevent+=new Marryhandler (Friend3. SendMessage);
Bridegroom. Onmarriagecoming ("Friend,i would marry!!");
Console.readkey ();
}
}

public class Friend
{
public string Name;
Public Friend (string name)
{
Name=name;
}
event handler, which needs to conform to the definition of the Marryhandler delegate
public void SendMessage (object S,marryeventargs e)
{
Console.WriteLine (e.message);
Console.WriteLine (this. Name+ "received, then on time to participate");
}
}

The EventArgs class is extended with a custom Marryeventargs event class, at which time Marryeventargs with an event argument named message, and then in the SendMessage method of the subscription object, through E. The message method obtains the event data and outputs the event data.

3. The nature of the event

From the above example we can know that the event is on the basis of the delegate. So, what kind of relationship do they have, and this has to be spied on by reflector.

Simple Source code:

Namespace spying on the nature of events
{
Class Program
{
public delegate void Marryhanler (string msg);

public event Marryhanler Marryevent;
static void Main (string[] args)
{
}
}
}

Reflector the results of the anti-compilation:

Figure 1

Figure 2

Figure 3

Figure 4

As you can see, the C # event is compiled into a code snippet that contains two public methods, one with the add_ prefix and the other with a remove_ prefix followed by the name of the C # event.

In the Add_ method, implemented by invoking the Delegate.combine () method (where the red box is in Figure 3), the Delegate.combine () method combines multiple delegates in order to be a multicast delegate.

In the Remove_ method, the Delegate.remove () method is also used.

From the above four graphs can be summed up:

The event of C # is a special multicast delegate, and the event defaults to a private delegate type variable (the red box in Figure 2), which holds a reference to the event-handling method, and the variable of that delegate type is private and can only be accessed from the class that defines the event.

From the anti-compilation code you can see that the attributes we have learned are similar. However, unlike events, where a set access and get accessor are defined in a property, the essence of the two accessors is two methods prefixed with "get_" and "set_". property is used to access private fields in a class, and C # events can also be thought of as "properties of a delegate field," So you can access the private delegate field through events, which is why the C # event attribute exists. The C # event mechanism conforms to the object-oriented encapsulation feature and is more secure in code.

Decryption of the event

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.