C # Event Delegation tutorial

Source: Internet
Author: User

This is what I saw in the Help document yesterday, it is very good, this is the IDE itself, so, interested, can be found in the Help, convenient and authoritative, written also very easy to understand. Posted up, let's see, this help document is all good stuff ah.

"Events" in C # is a way for a class to provide notification to customers of that class when something interesting happens. The most common use of events is for graphical user interfaces; Typically, classes that represent controls in the interface have events that are notified when the user makes certain actions, such as clicking a button, on the control.

However, events may not be used for graphical interfaces only. Events provide an often useful way for objects to signal state changes that may be useful to the client of that object. Events are important building blocks for creating classes that can be reused in a large number of different programs.

Use a delegate to declare an event. If you have not yet learned the delegation tutorial, you should first learn it before continuing. Recall that the delegate object encapsulates a method so that the method can be called anonymously. An event is a method that a class allows a client to provide a delegate for which the methods should be invoked when the event occurs. When an event occurs, the delegate that its customer provides to it is invoked.

In addition to declaring events, invoking events, and hooking up with events, the following topics are covered in this tutorial:

Events and inheritance
Events in an interface
The. NET Framework Guide
Example 1
The following simple example shows a listwithchangedevent class that is similar to the standard ArrayList class and invokes the Changed event whenever the contents of the list change. Such a general-purpose class can be used in a variety of ways in large programs.

For example, a word processor might contain a list of open documents. Whenever the list changes, you may need to notify many different objects in the word processor so that you can update the user interface. With events, code that maintains a list of documents does not need to know who needs to be notified, and once the list of documents has changed, the event is automatically invoked to correctly notify each object that needs to be notified. Using events increases the degree of modularity of your program.

Events1.cs
Using System;
Namespace Mycollections
{
Using System.Collections;

A delegate type for hooking the up change notifications.
public delegate void Changedeventhandler (object sender, EventArgs e);

A class that works just like ArrayList, but sends event
Notifications whenever the list changes.
public class Listwithchangedevent:arraylist
{
An event so clients can use to be notified whenever the
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 the methods 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 TestEvents
{
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 would be called whenever the list changes.
private void ListChanged (object sender, EventArgs e)
{
Console.WriteLine ("This is called 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 the event fires.
This is called the event fires.
Code Discussion
Declaring an event to declare an event within a class, you must first declare the delegate type of the event, if it has not been declared.
public delegate void Changedeventhandler (object sender, EventArgs e);
A delegate type defines a set of parameters that are passed to the method that handles the event. Multiple events can share the same delegate type, so you need to perform this step only if you have not yet declared any appropriate delegate types.

Next, declare the event itself.

public event Changedeventhandler Changed;
The method of declaring the event is similar to the field declaring the delegate type, except that the keyword event is preceded by the event declaration, followed by the modifier. Events are often declared as public events, but allow any accessible modifiers.

After invoking an event class to declare an event, you can handle the event in the same way as a field that handles the indicated delegate type. If no client hooks the delegate to the event, the field is empty, otherwise the field references the delegate that should be invoked when the event is invoked. Therefore, when an event is invoked, it is usually checked for empty before the event is invoked.
if (Changed!= null)
Changed (this, e);
The calling event can only be done from within the class that declares the event.

With an event hook from outside the class that declares the event, the event looks like a field, but access to the field is very limited. Only the following actions are available:
Compose a new delegate on this field.
Removes a delegate from a field (possibly a composite field).
Use the + = and-= operators to complete this operation. To begin receiving an event call, the client code first creates a delegate of the event type that references the method that should be invoked from the event. It then uses + + to write the delegate to any other delegate that the event might connect to.

Add "ListChanged" to the Changed event on "List":
List.changed + = new Changedeventhandler (listchanged);
When the client code finishes receiving an event call, it removes its delegate from the event using operator-=.

Detach the event and delete the list:
list.changed-= new Changedeventhandler (listchanged);
Events and inheritance
When you create a generic component from which you can derive, events sometimes appear to be problematic. Because events can only be invoked from within the class that declares them, the derived class cannot directly invoke events declared within the base class. Although this is sometimes desirable, it is often more appropriate to allow derived classes to invoke events freely. This is usually done by creating a protected invocation method for the event. A derived class can call this event by calling the calling method. For greater flexibility, the calling method is usually declared virtual, which allows the derived class to override the calling method. This allows derived classes to intercept events that are being invoked by the base class, and it is possible to perform its own processing on these events.

In the previous example, this was implemented using the OnChanged method. Derived classes can invoke or override the method, if necessary.

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

The. NET Framework Guide
Although the C # language allows events to use any delegate type, the. NET Framework has some more stringent guidelines for the type of delegate that should be used for the event. If you intend to use your components with the. NET Framework, you may want to follow these guidelines.

The. NET Framework Guide indicates that the delegate type used for the event should take two parameters: an "E" parameter indicating the object source parameter of the event source and any other related information that encapsulates the event. The type of the "E" parameter should derive from the EventArgs class. For events that do not use any other information, the. NET Framework has defined an appropriate delegate type: EventHandler.

Example 2
The following example is a modified version of "Example 1" that adheres to the. NET Framework guidelines. The 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
Notifications whenever the list changes:
public class Listwithchangedevent:arraylist
{
An event so clients can use to be notified whenever the
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 the methods 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 TestEvents
{
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 would be called whenever the list changes:
private void ListChanged (object sender, EventArgs e)
{
Console.WriteLine ("This is called 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 are called when the event fires.
This is called 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.