Presentation is loading. Please wait.

Presentation is loading. Please wait.

Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.

Similar presentations


Presentation on theme: "Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces."— Presentation transcript:

1 Module 8: Delegates and Events

2 Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces

3  Delegates Delegate Scenario Declaring a Delegate Instantiating a Delegate Calling a Delegate

4 Delegate Scenario 1 - Change in switch position invokes switch’s OnFlip method 2 - OnFlip Method invokes delegate 3 - Delegate invokes light’s OnFlipCallback method 4 - OnFlipCallback method changes light’s state OnFlip method Switch Object OnFlipCallback method Light Object Delegate object OnFlip method Switch Object

5 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 string and has a void return type delegate void MyDelegate1(string s); // declares a delegate for a method that takes a single // argument of type string and has a void return type delegate void MyDelegate1(string s);

6 Instantiating a Delegate A Delegate Object Is Created with the new Operator Delegate Objects Are Immutable // instantiating a delegate to a static method Hello // in the class MyClass MyDelegate1 a = new MyDelegate1(MyClass.Hello); // instantiating a delegate to an instance method // AMethod in object p MyClass p = new MyClass(); MyDelegate1 b = new MyDelegate1(p.AMethod); // instantiating a delegate to a static method Hello // in the class MyClass MyDelegate1 a = new MyDelegate1(MyClass.Hello); // instantiating a delegate to an instance method // AMethod in object p MyClass p = new MyClass(); MyDelegate1 b = new MyDelegate1(p.AMethod);

7 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 Hello with the parameter "World" a("World"); // given the previous delegate declaration and // instantiation, the following invokes MyClass ' // static method Hello with the parameter "World" a("World");

8 Demonstration: Using Delegates

9  Multicast Delegates Multicast Delegate Scenario Single vs. Multicast Delegates Creating and Invoking Multicast Delegates C# Language-Specific Syntax Delegate Details

10 Multicast Delegate Scenario 2 - OnFlip method invokes multicast delegate1 4 - OnFlipCallback method changes light1’s state 3 - delegate1 invokes light1’s OnFlipCallback 7 - OnFlipCallback method changes light2’s state 6 - delegate2 invokes light2’s OnFlipCallback OnFlip method Switch Object OnFlipCallback method Light1 Object OnFlipCallback method Light2 Object Multicast delegate1 object Multicast delegate2 object Invocation list 5 - delegate2 is invoked 1 - Change in switch position invokes switch’s OnFlip method OnFlip method Switch Object

11 Single vs. Multicast Delegates All Delegates Have an Invocation List of Methods That Are Executed When Their Invoke Method is Called Single-Cast Delegates: Derived Directly From System.Delegate Invocation list contains only one method Multicast Delegates: Derived from System.MulticastDelegate Invocation list may contain multiple methods Multicast delegates contain two static methods to add and remove references from invocation list: Combine and Remove Use GetInvocationList to Obtain an Invocation List as an Array of Delegate References Use a Delegate’s Target and Method Properties to Determine: Which object will receive the callback Which method will be called

12 Creating and Invoking Multicast Delegates // assign to c the composition of delegates a and b c = (MyDelegate2)Delegate.Combine(a, b); // assign to d the result of removing a from c d = (MyDelegate2)Delegate.Remove(c, a); // Iterate through c's invocation list // and invoke all delegates except a Delegate[] DelegateList = c.GetInvocationList(); for (int i = 0; i < DelegateList.Length; i++) { if (DelegateList[i].Target != aFoo1) { ((MyDelegate2) DelegateList[i])(); } // assign to c the composition of delegates a and b c = (MyDelegate2)Delegate.Combine(a, b); // assign to d the result of removing a from c d = (MyDelegate2)Delegate.Remove(c, a); // Iterate through c's invocation list // and invoke all delegates except a Delegate[] DelegateList = c.GetInvocationList(); for (int i = 0; i < DelegateList.Length; i++) { if (DelegateList[i].Target != aFoo1) { ((MyDelegate2) DelegateList[i])(); }

13 C# Language-Specific Syntax C# Delegates That Return Void Are Multicast Delegates In C#, Use the + and - Operators to Add and Remove Invocation List Entries Less verbose than Combine and Remove methods MyDelegate a, b, c, d; a = new MyDelegate(Foo); b = new MyDelegate(Bar); c = a + b; // Compose two delegates to make another d = c - a; // Remove a from the composed delegate a += b;// Add delegate b to a ' s invocation list a -= b;// Remove delegate b from a ' s list MyDelegate a, b, c, d; a = new MyDelegate(Foo); b = new MyDelegate(Bar); c = a + b; // Compose two delegates to make another d = c - a; // Remove a from the composed delegate a += b;// Add delegate b to a ' s invocation list a -= b;// Remove delegate b from a ' s list

14 Demonstration: Multicast Delegates

15 Delegate Details A Delegate Declaration Causes the Compiler to Generate a New Class // delegate void MyDelegate3(string val); class MyDelegate3 : System.MulticastDelegate { public MyDelegate3(object obj, methodref mref) : base (obj, mref) { //... } public void virtual Invoke(string val) { //... } }; // delegate void MyDelegate3(string val); class MyDelegate3 : System.MulticastDelegate { public MyDelegate3(object obj, methodref mref) : base (obj, mref) { //... } public void virtual Invoke(string val) { //... } };

16  Events Declaring an Event Connecting to an Event Raising an Event.NET Framework Guidelines

17 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; //... } // MouseClicked delegate declared public delegate void MouseClickedEventHandler(); public class Mouse { // MouseClicked event declared public static event MouseClickedEventHandler MouseClickedHandler; //... }

18 Connecting to an Event Connect by Combining Delegates Disconnect by Removing Delegates // 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 MouseClickedEventHandler(MouseClicked); // 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 MouseClickedEventHandler(MouseClicked);

19 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(); if (MouseClickedHandler != null) MouseClickedHandler();

20 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; public class SwitchFlippedEventArgs : EventArgs { //... } public delegate void SwitchFlippedEventHandler( object sender, SwitchFlippedEventArgs e); public event SwitchFlippedEventHandler SwitchFlippedHandler;.NET Framework Guidelines

21 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

22 Lab 8: Creating a Simple Chat Server

23 Review Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces


Download ppt "Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces."

Similar presentations


Ads by Google