Sie sind auf Seite 1von 5

Why Delegates?

Necessary Indirection: enables us to write our code without our code having to "know" the specific method that will ultimately be called at a specific point. invoke a delegate instance which, in turn, calls any methods that are registered with the delegate instance. Synchronous and Asynchronous Method Invocation common reason to call methods via delegate instances is to invoke methods asynchronously case the called method runs on a separate thread pool thread.

in which

Event Foundation delegates provide a necessary layer of indirection between event publishers and their subscribers. Meaning of Multicast: The meaning of "multicast" in System.MulticastDelegate is that the delegate is capable of holding references to multiple methods Delegates are Immutable when you register a method with a delegate, what is happening is that a new delegate instance is created that includes the additional method in its invocation list.

4. The Relationship Between Delegates and Events


delegates act as intermediaries between the code that raises events and the code that executes in response thereby decoupling event publishers from their subscribers.

Event Handlers (in general)


"event handler," only in reference to the delegate, while using the expression, "event handling method," in reference to any method registered with the delegate.

Anonymous Methods
An anonymous method is a block of code that you pass to a delegate (rather than passing the name of a method to be referenced by the delegate). The method is said to be "anonymous" because you are making use of it without knowing its name (it has no name in your source code).
static void EventHandlingMethod(object sender, EventArgs e) { Console.WriteLine("Handled by a named method"); } thePublisher.EventName += new MyEventHandlerDelegate(EventHandlingMethod);

The above logic can be rewritten with an anonymous method, like this:

thePublisher.EventName += delegate { Console.WriteLine("Handled by anonymous method"); };

following code demonstrates three options for registering an event handling method with an event. The first demonstrates the explicit approach that works with all versions of the .NET Framework. The second demonstrates delegate inference. The third demonstrates the use of an anonymous method:
// Option 1 - explicit delegate creation with a named method thePublisher.EventName += new MyEventHandlerDelegate(EventHandlingMethod); // Option 2 - delegate inference thePublisher.EventName += EventHandlingMethod; // Option 3 - anonymous method thePublisher.EventName += delegate(object sender, EventArgs e) { Console.WriteLine("handled by anonymous method"); // You can access the sender and e parameters here if necessary }; // Event handling method used in options 1 and 2 static void EventHandlingMethod(object sender, EventArgs e) { Console.WriteLine("Handled by a named method"); }

Conventions

Event Publisher Conventions


Event Name

Examples for events raised before state change:


y y y FileDownloading TemperatureChanging MailArriving

Examples for events raised after state change:


y y y FileDownloadCompleted TemperatureChanged MailArrived

System.EventArgs Subclass (where applicable) The name of your EventArgs subclass should be the name of the event, with 'EventArgs' appended

Example EventArgs subclass names:

y y y

DownloadCompletedEventArgs TemperatureChangedEventArgs MailArrivedEventArgs

Event Handler (delegate) Name

y If you are using .NET Framework 2.0 or newer (for 'both' publishers and subscribers), then you can make use of the generic System.EventHandler<TEventArgs> delegate y If you create your own delegate, then the delegate name should be comprised of the event name, with the word, 'Handler' appended Example custom event handler (delegate) names:
y y y DownloadCompletedHandler TemperatureChangedHandler MailArrivedHandler

Event Handler (delegate) Signature 1.The delegate should always return void. delegate, by design, acts as an intermediary between the event publisher and its subscribers. 2.The first parameter should be of the object type and should be named sender. 3.The second parameter should be named 'e' and should be of the System.EventArgs type or your custom subclass of System.EventArgs (e.g., MailArrivedEventArgs). Event Declaration Assuming the event is to be made available to code outside of the publishing class, the event would be declared with the public keyword (to make it accessible to code outside of the publishing class).
public event System.EventHandler<mailarrivedeventargs> MailArrived;

Example (makes use of a custom event handler):


public delegate void MailArrivedHandler (object sender, MailArrivedEventArgs e); public event MailArrivedHandler<mailarrivedeventargs> MailArrived;

Method That Raises the Event The name of this method should be the word On with the event name appended.
OnDownloadCompleted(DownloadCompletedEventArgs) { // Raise event here }

Event Subscriber Conventions


Event Handling Method Name The convention implemented by Visual Studio, when it automatically creates an event handling method stub, is to name the method as (1) the name of the object raising the event; followed by (2) an underscore character; with (3) the event name appended.

Examples:
y y y downloader_DownloadCompleted weatherStation_TemperatureChanged mailManager_OnMailArrived

nother convention is Specifically, the name of the method should be the word On with the event name appended.

Examples:
y y y OnDownloadCompleted OnTemperatureChanged OnMailArrived

Event Handling Method Signature


void DownloadManager_DownloadCompleted(object sender, DownloadCompletedEventArgs e) { // event handling code goes here }

Subscribing to the Event (code that registers the Event Handling Method with the Event)

To register a method with an event, use the += syntax, according to this pattern:
EventPublisherObject.EventName += new EventHandlerDelegateName(NameOfMethodToCall);

Unsubscribing from the Event (Code that Unregisters the Event Handling Method from the Event)
EventPublisherObject.EventName -= new EventHandlerDelegateName(NameOfMethodToCall); Example:

Event Publisher
public partial class Form1: Form

// delegate the subscribers must implement.


public delegate void evenhandler();

// The event we publish


public event evenhandler OnClick;

// The method which fires the Event


private void button1_Click(object sender, EventArgs e) {

// Check if there are any Subscribers


if (this.OnClick != null) {

// Call the Event


OnClick(); } }

} Event Subscribers
public partial class Form2 : Form { public Form2() { InitializeComponent(); Form1 frm1 = new Form1(); // subscribe to evenhandler event frm1.OnClick += new Form1.evenhandler(Add); frm1.ShowDialog(); }

// The method that implements the functionality


public void Add() { MessageBox.Show("add method"); } }

The publisher and the subscribers are decoupled by the delegate.

Das könnte Ihnen auch gefallen