C # event delegation tutorial

Source: Internet
Author: User

This is what I saw when I checked the help document yesterday. It is very good. It is provided by IDE. If you are interested, you can find it in the Help area, which is convenient, authoritative, and easy to understand. Paste it and let's take a look. The help documentation is full of good stuff.

In C #, "events" are a way for classes to notify customers of objects that have some interesting things. The most common purpose of an event is to use a graphical user interface. Generally, it indicates that the control class in the interface has some events. When you perform some operations on the control (such as clicking a button, these events will be notified.

However, events may not be used only for graphic interfaces. Events provide an object with a commonly useful method to signal state changes that may be useful to customers of the object. Events are important construction blocks for creating classes. These classes can be reused in a large number of different programs.

Use delegation to declare events. If you have not learned the "delegate tutorial", you should first learn it and then continue. Recall that the delegate object encapsulates a method so that this method can be called anonymously. An event is a method that allows the customer to delegate methods (the methods should be called when an event occurs) to it. When an event occurs, the delegate that the customer provides to it will be called.

In addition to declaring events, calling events, and event-linked examples, this tutorial also introduces the following topics:

Events and inheritance
Events in the interface
. NET Framework Guide
Example 1
The following simple example shows a listwithchangedevent class, which is similar to the standard arraylist class and calls the changed event whenever the list content changes. Such a general-purpose class can be used in many ways in large programs.

Example
For example, a word processor may contain a list of opened documents. When this list is changed, you may need to notify many different objects in the word processor to update the user interface. Use events to maintain the generation of the document list
You do not need to know who to notify. Once the document list is changed, this event is automatically called to correctly notify every object to be notified. Using events improves program modularization.

// Events1.cs
Using system;
Namespace mycollections
{
Using system. collections;

// A delegate type for hooking up change configurations.
Public Delegate void changedeventhandler (Object sender, eventargs E );

// A class that works just like arraylist, but sends event
// Configurations whenever the list changes.
Public class listwithchangedevent: arraylist
{
// An event that clients can use to be notified whenever
// Elements of the list change.
Public event changedeventhandler changed;

// Invoke the changed event; called whenever list changes
Protected virtual void onchanged (eventargs E)
{
If (changed! = NULL)
Changed (this, e );
}

// Override some of the methods that can change the list;
// Invoke event after each
Public override int add (object value)
{
Int I = base. Add (value );
Onchanged (eventargs. Empty );
Return I;
}

Public override void clear ()
{
Base. Clear ();
Onchanged (eventargs. Empty );
}

Public override object this [int Index]
{
Set
{
Base [Index] = value;
Onchanged (eventargs. Empty );
}
}
}
}

Namespace testeven TS
{
Using mycollections;

Class eventlistener
{
Private listwithchangedevent list;

Public eventlistener (listwithchangedevent List)
{
List = List;
// Add "listchanged" to the changed event on "list ".
List. Changed + = new changedeventhandler (listchanged );
}

// This will be called whenever the list changes.
Private void listchanged (Object sender, eventargs E)
{
Console. writeline ("this is called when the event fires .");
}

Public void detach ()
{
// Detach the event and delete the list
List. Changed-= new changedeventhandler (listchanged );
List = NULL;
}
}

Class Test
{
// Test the listwithchangedevent class.
Public static void main ()
{
// Create a new list.
Listwithchangedevent list = new listwithchangedevent ();

// Create a class that listens to the list's change event.
Eventlistener listener = new eventlistener (list );

// Add and remove items from the list.
List. Add ("item 1 ");
List. Clear ();
Listener. Detach ();
}
}
}
Output
This is called when the event fires.
This is called when the event fires.
Code Discussion
To declare an event in a class, you must first declare the delegate type of the event (if not declared ).
Public Delegate void changedeventhandler (Object sender, eventargs E );
The delegate type defines a set of parameters passed to the method for processing the event. Multiple events can share the same delegate type. Therefore, this step is required only when no suitable delegate type is declared.

Next, declare the event itself.

Public event changedeventhandler changed;
The method for declaring an event is similar to that for declaring a delegate type field, except that the keyword event is before the event declaration and behind the modifier. Events are usually declared as public events, but any accessable modifier is allowed.

After an event is declared, the event can be handled as if it were a field of the indicated delegate type. If no customer associates the delegate with this event, this field is blank; otherwise, this field references the delegate that should be called when the event is called. Therefore, when calling an event, you must first check whether it is empty and then call the event.
If (changed! = NULL)
Changed (this, e );
An event can be called only from the class that declares the event.

Events are linked to events. The event is like a field, but access to this field is very restricted. You can only perform the following operations:
Write a new delegate on this field.
Remove a delegate from a field (possibly a compound field.
Use the + = and-= operators to complete this operation. To start receiving event calls, the customer code first creates an event-type delegate that references methods called from the event. Then it uses + = to write the delegate to any other delegate that the event may be connected.

// Add "listchanged" to the changed event on "list ":
List. Changed + = new changedeventhandler (listchanged );
After the Customer Code completes receiving the event call, it will use the operator-= to remove its delegate from the event.

// Detach the event and delete the list:
List. Changed-= new changedeventhandler (listchanged );
Events and inheritance
When
When you create a common component that can be derived from it, the event may sometimes become a problem. Because events can only be called from the declared classes, derived classes cannot directly call events declared within the base class. Although
However, this is sometimes necessary, but it is more appropriate to allow the derived class to call events freely. This is usually done by creating a protected call method for the event. By calling this method, the derived class can call this event.
For greater flexibility, call methods are usually declared as virtual, which allows the derived class to override the call method. This allows the derived class to intercept the events being called by the base class and possibly execute its own location on these events.
.

In the previous example, this is implemented using the onchanged method. If necessary, the derived class can call or override this method.

Events in the interface
Another difference between an event and a field is that an event can be placed in an interface, but a field cannot. When implementing an interface, the implementation class must provide corresponding events in the class that implements the interface.

. NET Framework Guide
Although the C # language allows an event to use any delegate type, ". NET Framework" provides more rigorous guidelines for the delegate type used for the event. If you plan to use your components with the. NET Framework, you may want to follow these guidelines.

". Net
The framework guide indicates that the delegate type used for the event should use two parameters: the "Object source" parameter indicating the event source and the "e" parameter indicating any other relevant information of the event. Class of "E" parameter
Type should be derived from the eventargs class. For events that do not use any other information, ". net
Framework "has defined an appropriate delegate type: eventhandler.

Example 2
The following example shows how to modify the version of "Example 1". It complies with the ". NET Framework" guide. This example uses the eventhandler delegate type.

// Events2.cs
Using system;
Namespace mycollections
{
Using system. collections;

// A class that works just like arraylist, but sends event
// Configurications whenever the list changes:
Public class listwithchangedevent: arraylist
{
// An event that clients can use to be notified whenever
// Elements of the list change:
Public event eventhandler changed;

// Invoke the changed event; called whenever list changes:
Protected virtual void onchanged (eventargs E)
{
If (changed! = NULL)
Changed (this, e );
}

// Override some of the methods that can change the list;
// Invoke event after each:
Public override int add (object value)
{
Int I = base. Add (value );
Onchanged (eventargs. Empty );
Return I;
}

Public override void clear ()
{
Base. Clear ();
Onchanged (eventargs. Empty );
}

Public override object this [int Index]
{
Set
{
Base [Index] = value;
Onchanged (eventargs. Empty );
}
}
}
}

Namespace testeven TS
{
Using mycollections;

Class eventlistener
{
Private listwithchangedevent list;

Public eventlistener (listwithchangedevent List)
{
List = List;
// Add "listchanged" to the changed event on "list ":
List. Changed + = new eventhandler (listchanged );
}

// This will be called whenever the list changes:
Private void listchanged (Object sender, eventargs E)
{
Console. writeline ("this is called when the event fires .");
}

Public void detach ()
{
// Detach the event and delete the list:
List. Changed-= new eventhandler (listchanged );
List = NULL;
}
}

Class Test
{
// Test the listwithchangedevent class:
Public static void main ()
{
// Create a new list:
Listwithchangedevent list = new listwithchangedevent ();

// Create a class that listens to the list's change event:
Eventlistener listener = new eventlistener (list );

// Add and remove items from the list:
List. Add ("item 1 ");
List. Clear ();
Listener. Detach ();
}
}
}
Output
This is called when the event fires.
This is called when the event fires.

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.