
10266A_11.ppt
- Количество слайдов: 22
Module 11 Decoupling Methods and Handling Events
Module Overview • Declaring and Using Delegates • Using Lambda Expressions • Handling Events
Lesson 1: Declaring and Using Delegates • Why Decouple an Operation from a Method? • Defining a Delegate • Invoking a Delegate • Defining Anonymous Methods
Why Decouple an Operation from a Method? • Methods determined dynamically at run time • Method A or method B or method C • Callback methods • Enable you to specify a method (or methods) to run when an asynchronous method call completes, particularly when you use third-party assemblies • Multicast operations • Method A and method B and method C Implemented by using delegates, which are basically references to methods
Defining a Delegate Define a delegate by using the delegate keyword public delegate bool is. Valid. Delegate(); Create an instance of the delegate public is. Valid. Delegate is. Valid = null; Add method references to the delegate by using the += operator is. Valid += Check. State. Valid; is. Valid += new is. Valid. Delegate(Check. Control); Remove method references from the delegate by using the -= operator is. Valid -= Check. State. Valid;
Invoking a Delegate Always check a delegate is not null before invoking it! Invoke a delegate synchronously by using method-like syntax if (is. Valid != null) { is. Valid(); } Invoke a delegate asynchronously by using the Begin. Invoke and End. Invoke methods if (is. Valid != null) { is. Valid. Begin. Invoke(); }
Defining Anonymous Methods Use the overloaded delegate keyword Add the Optionally specify the parameter anonymous method as a handler for a delegate my. Delegate. Instance += new my. Delegate (delegate (int parameter) { // Perform operation. return 10; }); names and types for the anonymous method Add the method body for the anonymous method Do not specify a return type; the compiler will work out the return type based on the context
Lesson 2: Using Lambda Expressions • What Is a Lambda Expression? • Defining Lambda Expressions • Variables Scope in Lambda Expressions
What Is a Lambda Expression? A lambda expressions is an expression that returns a method Lambda expressions are defined by using the => operator Lambda expressions use a natural and concise syntax x => x * x This code example can be read as: Given x calculate x * x The parameter and return types are inferred
Defining Lambda Expressions A simple expression where the type of the x parameter is inferred from the context x => x * x An expression that uses a Visual C# statement block instead of a simple expression x => { return x * x ; } An expression that calls a method and takes no parameters () => my. Object. My. Method(0) An expression where the parameter type is stated explicitly (int x) => x / 2 An expression with multiple parameters and a parameter passed by reference (ref int x, int y) { x++; return x / y; }
Variable Scope in Lambda Expressions • Lambda expressions can use any variables that are in scope when they are declared • Lambda expressions can define variables string name; // Class level field. . void my. Method() { int count = 0; del += new My. Delegate(() => { int temp = 10; Check. Name(name); count++; // Doe something more interesting. }); } Using an outer variable in a lambda expression can extend its life cycle Use this feature carefully!
Lesson 3: Handling Events • What Is an Event? • Defining an Event • Using Events • Best Practices for Using Events • Using Events in Graphical Applications • Demonstration: Using Events
What Is an Event? An event provides a mechanism for informing consuming application of a change of state or other occurrence in a type Events are based on delegates Unlike an instance of a delegate, an event can be raised (invoked) only by the containing class or a derivative of it Consuming classes can subscribe to the event, adding references to methods that need to run when an event is raised Events are used extensively in the. NET Framework; nearly all Windows Presentation Foundation (WPF) controls use them
Defining an Event Define a delegate on which the event is based; the delegate should be at least as visible as the event public delegate void My. Event. Delegate(object sender, Event. Args e); public event My. Event. Delegate My. Event = null; Use the event Specify the delegate Specify a name for keyword type the event You can define an event in an interface
Using Events To subscribe to an event, use the += compound assignment operator in the same way you add a method reference to a delegate My. Event += new My. Event. Delegate(my. Handling. Method); To unsubscribe from an event, use the -= compound assignment operator My. Event -= my. Handling. Method; To raise an event, use the event name and specify the parameters in parentheses, similar to calling a method if (My. Event != null) { Event. Args args = new Event. Args(); My. Event(this, args); } Always check an event is not null before raising it!
Best Practices for Using Events ü Use the standard event signature ü Use a protected virtual method to raise an event ü Do not pass null to an event
Using Events in Graphical Applications Step 1 Step 2 Step 3 Step 4 Step 5 Step 6 Step 4 a Background. Worker Do. Work Run. Worker. Async Report. Progress. Changed Run. Worker. Completed Cancel. Async Step 4 b Step 4 c
Demonstration: Using Events In this demonstration you will see how to: • Create a delegate • Create an event based on the delegate • Create an On method to raise the event • Create a simple application to respond to events raised
Lab: Decoupling Methods and Handling Events • Exercise 1: Raising and Handling Events • Exercise 2: Using Lambda Expressions to Specify Code Logon information Virtual machine 10266 A-GEN-DEV User name Student Password Pa$$w 0 rd Estimated time: 60 minutes
Lab Scenario
Lab Review • If you define a delegate for an event, when should you use the Event. Args class? • What are the advantages of defining an On method to raise an event? • What is the primary difference between exposing an instance of a delegate and exposing an event? • When you define a lambda expression, what are the rules for using type inference with input parameters?
Module Review and Takeaways • Review Questions • Best Practices