Presentation is loading. Please wait.

Presentation is loading. Please wait.

Delegates & Events 1.

Similar presentations


Presentation on theme: "Delegates & Events 1."— Presentation transcript:

1 Delegates & Events 1

2 Delegates Delegates are how C# defines a dynamic interface between two methods Same goal as function pointers in C Delegates are type-safe A delegate object holds a reference to a method with a pre-defined signature A signature is simply the argument list and return type of the method The keyword delegate specifies that we are defining a delegate object

3 Delegates Consists of two parts: a delegate type and a delegate instance A delegate type looks like an (abstract) method declaration, preceded with the delegate keyword A delegate instance creates an instance of this type, supplying it with the name of a real method to attach to

4 Declaring a Delegate A Delegate Declaration Defines a Type That Encapsulates a Method with a Particular Set of Arguments and Return Type // declares a delegate for a method that takes a single // argument of type double and has a void return type delegate void MyDelegate(double d);

5 Instantiating a Delegate
A Delegate Object Is Created with the new Operator Delegate Objects Are Immutable The method signature must match the delegate signature // instantiating a delegate to a static method Calculate // in the class MyClass MyDelegate a = new MyDelegate(MyClass.Calculate); // instantiating a delegate to an instance method // AMethod in object p MyClass p = new MyClass(); MyDelegate b = new MyDelegate(p.AMethod);

6 Calling a Delegate Use a Statement Containing:
The name of the delegate object Followed by the parenthesized arguments to be passed to the delegate // given the previous delegate declaration and // instantiation, the following invokes MyClass' // static method Calculate with the parameter 0.123 a(0.123);

7 Chaining (Multicast) Delegate
Delegate objects can be initialized with several method calls using the += operator The method calls can then be invoked in a chain by passing the correct arguments to the delegate object Essentially it amounts to calling methods through a proxy object and is a powerful mechanism for event handling as we shall see Passing method calls into objects is then equivalent to passing delegate objects

8 Chaining (Multicast) Delegate
A delegate instance is actually a container of callback functions. It can hold a list of values. The operators += and -= are defined to add and remove values. The operator = clears the list and assigns it to the rhs

9 Declaring an Event Declare the Delegate Type for the Event
Declare the Event Like the field of delegate type preceded by an event keyword // MouseClicked delegate declared public delegate void MouseClickedEventHandler(); public class Mouse { // MouseClicked event declared public static event MouseClickedEventHandler MouseClickedHandler; //... }

10 Connecting to an Event An application can then register its interest in an event by adding an initialized delegate object to the event using the += operator // Client’s method to handle the MouseClick event private void MouseClicked() { //... } //... // Client code to connect to MouseClicked event Mouse.MouseClickedHandler += new MouseClickedEventHandler(MouseClicked); // Client code to break connection to MouseClick event Mouse.MouseClickedHandler -= new

11 Raising an Event Check Whether Any Clients Have Connected to This Event If the event field is null, there are no clients Raise the Event by Invoking the Event’s Delegate if (MouseClickedHandler != null) MouseClickedHandler();

12 .NET Framework Guidelines
Name Events with a Verb and Use Pascal Casing Use "Raise" for Events, Instead of "Fire" Event Argument Classes Extend System.EventArgs Event Delegates Return Void and Have Two Arguments Use a Protected Virtual Method to Raise Each Event public class SwitchFlippedEventArgs : EventArgs { ... } public delegate void SwitchFlippedEventHandler( object sender, SwitchFlippedEventArgs e); public event SwitchFlippedEventHandler SwitchFlippedHandler;

13 When to Use Delegates, Events, and Interfaces
Use a Delegate If: You basically want a C-style function pointer You want single callback invocation The callback should be registered in the call or at construction time, not through methods Use Events If: Client signs up for the callback function through methods More than one object will care Use an Interface If: The callback function entails complex behavior, such as multiple methods

14 Custom Event Example using System; namespace CustomEventExample { public delegate void ElapsedMinuteEventHandler(Object sender, MinuteEventArgs e); }

15 Custom Event Example using System; namespace CustomEventExample { public class MinuteEventArgs : EventArgs private DateTime date_time; public MinuteEventArgs(DateTime date_time) this.date_time = date_time; } public int Minute get { return date_time.Minute; }

16 Custom Event Example using System; namespace CustomEventExample { public class Publisher public event ElapsedMinuteEventHandler MinuteTick; public Publisher() { Console.WriteLine("Publisher Created"); } public void countMinutes() int current_minute = DateTime.Now.Minute; while (true) if (current_minute != DateTime.Now.Minute) Console.WriteLine("Publisher: {0}", DateTime.Now.Minute); onMinuteTick(new MinuteEventArgs(DateTime.Now)); current_minute = DateTime.Now.Minute; }//end if } // end countMinutes method public void onMinuteTick(MinuteEventArgs e) { if (MinuteTick != null) MinuteTick(this, e); } } // end Publisher class definition } // end CustomEventExample namespace

17 Custom Event Example using System; namespace CustomEventExample { public class Subscriber private Publisher publisher; public Subscriber(Publisher publisher) this.publisher = publisher; subscribeToPublisher(); Console.WriteLine("Subscriber Created"); } public void subscribeToPublisher() { publisher.MinuteTick += new ElapsedMinuteEventHandler(minuteTickHandler); } public void minuteTickHandler(Object sender, MinuteEventArgs e) { Console.WriteLine("Subscriber Handler Method: {0}", e.Minute); } } // end Subscriber class definition } // end CustomEventExample namespace

18 Custom Event Example using System; namespace CustomEventExample { public class MainApp public static void Main() Console.WriteLine("Custom Events are Cool!"); Publisher p = new Publisher(); Subscriber s = new Subscriber(p); p.countMinutes(); } // end main } //end MainApp class definition } // end CustomEventExample namespace

19 ?

20 References


Download ppt "Delegates & Events 1."

Similar presentations


Ads by Google