microsoft visual c 2008 step by step phần 6 potx

67 364 0
microsoft visual c 2008 step by step phần 6 potx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Chapter 16 Using Indexers 309 Implement an interface indexer in a class or structure In the class or structure that implements the interface, defi ne the indexer and implement the accessors. For example: struct RawInt : IRawInt { public bool this [ int index ] { get { } set { } } } Implement an interface indexer by using explicit interface implementation in a class or structure In the class or structure that implements the interface, explicitly name the interface, but do not specify the indexer accessibility. For example: struct RawInt : IRawInt { bool IRawInt.this [ int index ] { get { } set { } } } 311 Chapter 17 Interrupting Program Flow and Handling Events After completing this chapter, you will be able to:  Declare a delegate type to create an abstraction of a method signature.  Create an instance of a delegate to refer to a specifi c method.  Call a method through a delegate.  Defi ne a lambda expression to specify the code for a delegate.  Declare an event fi eld.  Handle an event by using a delegate.  Raise an event. Much of the code you have written in the various exercises in this book has assumed that statements execute sequentially. Although this is a common scenario, you will fi nd that it is sometimes necessary to interrupt the current fl ow of execution and perform another, more important, task. When the task has completed, the program can continue where it left off. The classic example of this style of program is the Microsoft Windows Presentation Foundation (WPF) form. A WPF form displays controls such as buttons and text boxes. When you click a button or type text in a text box, you expect the form to respond immediately. The application has to temporarily stop what it is doing and handle your input. This style of operation applies not just to graphical user interfaces but to any application where an opera- tion must be performed urgently—shutting down the reactor in a nuclear power plant if it is getting too hot, for example. To handle this type of application, the runtime has to provide two things: a means of indi- cating that something urgent has happened and a way of indicating the code that should be run when it happens. This is the purpose of events and delegates. We start by looking at delegates. Declaring and Using Delegates A delegate is a pointer to a method, and you can call it in the same way as you would call a method. When you invoke a delegate, the runtime actually executes the method to which the delegate refers. You can dynamically change the method that a delegate references so that 312 Part III Creating Components code that calls a delegate might actually run a different method each time it executes. The best way to understand delegates is to see them in action, so let’s work through an example. Note If you are familiar with C++, a delegate is similar to a function pointer. However, unlike function pointers, delegates are type-safe; you can make a delegate refer to only a method that matches the signature of the delegate, and you cannot call a delegate that does not refer to a valid method. The Automated Factory Scenario Suppose you are writing the control systems for an automated factory. The factory contains a large number of different machines, each performing distinct tasks in the production of the articles manufactured by the factory—shaping and folding metal sheets, welding sheets together, painting sheets, and so on. Each machine was built and installed by a specialist ven- dor. The machines are all computer-controlled, and each vendor has provided a set of APIs that you can use to control its machine. Your task is to integrate the different systems used by the machines into a single control program. One aspect on which you have decided to concentrate is to provide a means of shutting down all the machines, quickly if needed! Note The term API stands for application programming interface. It is a method, or set of methods, exposed by a piece of software that you can use to control that software. You can think of the Microsoft .NET Framework as a set of APIs because it provides methods that you can use to control the .NET common language runtime and the Microsoft Windows operating system. Each machine has its own unique computer-controlled process (and API) for shutting down safely. These are summarized here: StopFolding(); // Folding and shaping machine FinishWelding(); // Welding machine PaintOff(); // Painting machine Implementing the Factory Without Using Delegates A simple approach to implementing the shutdown functionality in the control program is as follows: class Controller { // Fields representing the different machines private FoldingMachine folder; private WeldingMachine welder; private PaintingMachine painter; Chapter 17 Interrupting Program Flow and Handling Events 313 public void ShutDown() { folder.StopFolding(); welder.FinishWelding(); painter.PaintOff(); } } Although this approach works, it is not very extensible or fl exible. If the factory buys a new machine, you must modify this code; the Controller class and the machines are tightly coupled. Implementing the Factory by Using a Delegate Although the names of each method are different, they all have the same “shape”: They take no parameters, and they do not return a value. (We consider what happens if this isn’t the case later, so bear with me!) The general format of each method is, therefore: void methodName(); This is where a delegate is useful. A delegate that matches this shape can be used to refer to any of the machinery shutdown methods. You declare a delegate like this: delegate void stopMachineryDelegate(); Note the following points:  Use the delegate keyword when declaring a delegate.  A delegate defi nes the shape of the methods it can refer to. You specify the return type (void in this example), a name for the delegate (stopMachineryDelegate), and any parameters (there are none in this case). After you have defi ned the delegate, you can create an instance and make it refer to a matching method by using the += compound assignment operator. You can do this in the constructor of the controller class like this: class Controller { delegate void stopMachineryDelegate(); private stopMachineryDelegate stopMachinery; // an instance of the delegate public Controller() { this.stopMachinery += folder.StopFolding; } } 314 Part III Creating Components This syntax takes a bit of getting used to. You add the method to the delegate; you are not actually calling the method at this point. The + operator is overloaded to have this new meaning when used with delegates. (You will learn more about operator overloading in Chapter 21, “Operator Overloading.”) Notice that you simply specify the method name and should not include any parentheses or parameters. It is safe to use the += operator on an uninitialized delegate. It will be initialized automati- cally. You can also use the new keyword to initialize a delegate explicitly with a single specifi c method, like this: this.stopMachinery = new stopMachineryDelegate(folder.StopFolding); You can call the method by invoking the delegate, like this: public void ShutDown() { this.stopMachinery(); } You use the same syntax to invoke a delegate as you use to make a method call. If the method that the delegate refers to takes any parameters, you should specify them at this time, between parentheses. Note If you attempt to invoke a delegate that is uninitialized and does not refer to any methods, you will get a NullReferenceException. The principal advantage of using a delegate is that it can refer to more than one method; you simply use the += operator to add methods to the delegate, like this: public Controller() { this.stopMachinery += folder.StopFolding; this.stopMachinery += welder.FinishWelding; this.stopMachinery += painter.PaintOff; } Invoking this.stopMachinery() in the Shutdown method of the Controller class automatically calls each of the methods in turn. The Shutdown method does not need to know how many machines there are or what the method names are. You can remove a method from a delegate by using the -= compound assignment operator: this.stopMachinery -= folder.StopFolding; Chapter 17 Interrupting Program Flow and Handling Events 315 The current scheme adds the machine methods to the delegate in the Controller constructor. To make the Controller class totally independent of the various machines, you need to make stopMachineryDelegate type public and supply a means of enabling classes outside Controller to add methods to the delegate. You have several options:  Make the delegate variable, stopMachinery, public: public stopMachineryDelegate stopMachinery;  Keep the stopMachinery delegate variable private, but provide a read/write property to provide access to it: public delegate void stopMachineryDelegate(); public stopMachineryDelegate StopMachinery { get { return this.stopMachinery; } set { this.stopMachinery = value; } }  Provide complete encapsulation by implementing separate Add and Remove methods. The Add method takes a method as a parameter and adds it to the delegate, while the Remove method removes the specifi ed method from the delegate (notice that you specify a method as a parameter by using a delegate type): public void Add(stopMachineryDelegate stopMethod) { this.stopMachinery += stopMethod; } public void Remove(stopMachineryDelegate stopMethod) { this.stopMachinery -= stopMethod; } If you are an object-oriented purist, you will probably opt for the Add/Remove approach. However, the others are viable alternatives that are frequently used, which is why they are shown here. Whichever technique you choose, you should remove the code that adds the machine methods to the delegate from the Controller constructor. You can then instantiate a 316 Part III Creating Components Controller and objects representing the other machines like this (this example uses the Add/Remove approach): Controller control = new Controller(); FoldingMachine folder = new FoldingMachine(); WeldingMachine welder = new WeldingMachine(); PaintingMachine painter = new PaintingMachine(); control.Add(folder.StopFolding); control.Add(welder.FinishWelding); control.Add(painter.PaintOff); control.ShutDown(); Using Delegates In the following exercise, you will create a delegate to encapsulate a method that displays the time in a text box acting as a digital clock on a WPF form. You will attach the delegate object to a class called Ticker that invokes the delegate every second. Complete the digital clock application 1. Start Microsoft Visual Studio 2008 if it is not already running. 2. Open the Delegates project located in the \Microsoft Press\Visual CSharp Step by Step \Chapter 17\Delegates folder in your Documents folder. 3. On the Debug menu, click Start Without Debugging. The project builds and runs. A form appears, displaying a digital clock. The clock displays the current time as “00:00:00,” which is probably wrong unless you happen to be reading this chapter at midnight. 4. Click Start to start the clock, and then click Stop to stop it again. Nothing happens. The Start and Stop methods have not been written yet. Your task is to implement these methods. 5. Close the form, and return to the Visual Studio 2008 environment. 6. Open the Ticker.cs fi le, and display it in the Code and Text Editor window. This fi le contains a class called Ticker that models the inner workings of a clock. Scroll to the bottom of the fi le. The class contains a DispatcherTimer object called ticking to arrange for a pulse to be sent at regular intervals. The constructor for the class sets this interval to 1 second. The class catches the pulse by using an event (you will learn how events work shortly) and then arranges for the display to be updated by invoking a delegate. C omplete the digital clock application Chapter 17 Interrupting Program Flow and Handling Events 317 Note The .NET Framework provides another timer class called System.Timers.Timer. This class offers similar functionality to the DispatcherTimer class, but it is not suitable for use in a WPF application. 7. In the Code and Text Editor window, fi nd the declaration of the Tick delegate. It is located near the top of the fi le and looks like this: public delegate void Tick(int hh, int mm, int ss); The Tick delegate can be used to refer to a method that takes three integer parameters and that does not return a value. A delegate variable called tickers at the bottom of the fi le is based on this type. By using the Add and Remove methods in this class (shown in the following code example), you can add methods with matching signatures to (and remove them from) the tickers delegate variable: class Ticker { public void Add(Tick newMethod) { this.tickers += newMethod; } public void Remove(Tick oldMethod) { this.tickers -= oldMethod; } private Tick tickers; } 8. Open the Clock.cs fi le, and display it in the Code and Text Editor window. The Clock class models the clock display. It has methods called Start and Stop that are used to start and stop the clock running (after you have implemented them) and a method called RefreshTime that formats a string to depict the time specifi ed by its three parameters (hours, minutes, and seconds) and then displays it in the TextBox fi eld called display. This TextBox fi eld is initialized in the constructor. The class also contains a private Ticker fi eld called pulsed that tells the clock when to update its display: class Clock { public Clock(TextBox displayBox) { this.display = displayBox; } 318 Part III Creating Components private void RefreshTime(int hh, int mm, int ss ) { this.display.Text = string.Format(“{0:D2}:{1:D2}:{2:D2}”, hh, mm, ss); } private Ticker pulsed = new Ticker(); private TextBox display; } 9. Display the code for the Window1.xaml.cs fi le in the Code and Text Editor window. Notice that the constructor creates a new instance of the Clock class, passing in the TextBox fi eld called digital as its parameter: public Window1() { clock = new Clock(digital); } The digital fi eld is the TextBox control displayed on the form. The clock will display its output in this TextBox control. 10. Return to the Clock.cs fi le. Implement the Clock.Start method so that it adds the Clock. RefreshTime method to the delegate in the pulsed object by using the Ticker.Add meth- od, as follows in bold type. The pulsed delegate is invoked every time a pulse occurs, and this statement causes the RefreshTime method to execute when this happens. The Start method should look like this: public void Start() { pulsed.Add(this.RefreshTime); } 11. Implement the Clock.Stop method so that it removes the Clock.RefreshTime method from the pulsed delegate by using the Ticker.Remove method, as follows in bold type. The Stop method should look like this: public void Stop() { pulsed.Remove(this.RefreshTime); } 12. On the Debug menu, click Start Without Debugging. 13. On the WPF form, click Start. The form now displays the correct time and updates every second. 14. Click Stop. The display stops responding, or “freezes.” This is because the Stop button calls the Clock.Stop method, which removes the RefreshTime method from the Ticker delegate; RefreshTime is no longer being called every second, although the timer continues to pulse. [...]... Framework class library includes generic versions of many of the collection classes and interfaces in the System.Collections.Generic namespace The following code example shows how to use the generic Queue class found in this namespace to create a queue of Circle objects: using System.Collections.Generic; Queue myQueue = new Queue(); Circle myCircle = new Circle(); myQueue.Enqueue(myCircle);... projects location text box, specify the location \Microsoft Press \Visual CSharp Step By Step\ Chapter 18 folder under your Documents folder 3.4 Click OK 3.5 On the File menu, click New Project 3 .6 In the New Project dialog box, click the Class Library icon 3.7 In the Name field, type BinaryTree 3.8 Click OK 4 In Solution Explorer, right-click Class1.cs and change the name of the file to Tree.cs Allow Visual. .. particular collection class as a detailed example, you will also notice in the 333 334 Part III Creating Components System.Collections.Queue class that you can create queues containing practically anything The following code example shows how to create and manipulate a queue of Circle objects: using System.Collections; Queue myQueue = new Queue(); Circle myCircle = new Circle(); myQueue.Enqueue(myCircle);... class “comparable” by implementing the System.IComparable interface and providing the CompareTo method In the example shown, the CompareTo method compares Circle objects based on their areas A circle with a larger area is considered to be greater than a circle with a smaller area class Circle : System.IComparable { public int CompareTo(object obj) { Circle circObj = (Circle)obj; // cast the parameter... an explicit cast denigrates much of the flexibility afforded by the object type It is very easy to write code such as this: Queue myQueue = new Queue(); Circle myCircle = new Circle(); myQueue.Enqueue(myCircle); Clock myClock = (Clock)myQueue.Dequeue(); // run-time error Although this code will compile, it is not valid and throws a System.InvalidCastException at run time The error is caused by trying... the Location to \Microsoft Press \Visual CSharp Step By Step\ Chapter 18 under your Documents folder 2.4 Click OK 3 If you are using Microsoft Visual C# 2008 Express Edition, perform the following tasks to create a new class library project: 3.1 On the Tools menu, click Options 3.2 In the Options dialog box, click Projects and Solutions in the tree view in the left pane 3.3 In the right pane, in the Visual. .. project 2 Display the Ticker.cs file in the Code and Text Editor window This file contains the declaration of the Tick delegate type in the Ticker class: public delegate void Tick(int hh, int mm, int ss); 3 Add a public event called tick of type Tick to the Ticker class, as shown in bold type in the following code: class Ticker { public delegate void Tick(int hh, int mm, int ss); public event Tick tick;... the System.Object class in the Microsoft NET Framework You can use this information to create highly generalized classes and methods For example, many of the classes in the System.Collections namespace exploit this fact, so you can create collections holding almost any type of data (You have already been introduced to the collection classes in Chapter 10, “Using Arrays and Collections.”) By homing in... the clock stops 15 Close the form, and return to Visual Studio 2008 If you want to continue to the next chapter Keep Visual Studio 2008 running and turn to Chapter 18 If you want to exit Visual Studio 2008 now On the File menu, click Exit If you see a Save dialog box, click Yes (if you are using Visual Studio 2008) or Save (if you are using Microsoft Visual C# 2008 Express Edition) and save the project... 0 The current instance is greater than the value of the parameter As an example, consider the Circle class that was described in Chapter 7, “Creating and Managing Classes and Objects,” and reproduced here: class Circle { public Circle(int initialRadius) { radius = initialRadius; } public double Area() { return Math.PI * radius * radius; } private double radius; } You can make the Circle class “comparable” . Start Microsoft Visual Studio 2008 if it is not already running. 2. Open the Delegates project located in the Microsoft Press Visual CSharp Step by Step Chapter 17Delegates folder in your Documents. the Clock.Start and Clock.Stop methods to subscribe to the event. You will also examine the Timer object, used by the Ticker class to obtain a pulse once each second. Rework the digital clock. you can create an instance and make it refer to a matching method by using the += compound assignment operator. You can do this in the constructor of the controller class like this: class Controller

Ngày đăng: 12/08/2014, 21:20

Từ khóa liên quan

Mục lục

  • Part III: Creating Components

    • Chapter 17: Interrupting Program Flow and Handling Events

      • Declaring and Using Delegates

        • The Automated Factory Scenario

        • Implementing the Factory Without Using Delegates

        • Implementing the Factory by Using a Delegate

        • Using Delegates

        • Lambda Expressions and Delegates

          • Creating a Method Adapter

          • Using a Lambda Expression as an Adapter

          • The Form of Lambda Expressions

          • Enabling Notifications with Events

            • Declaring an Event

            • Subscribing to an Event

            • Unsubscribing from an Event

              • Raising an Event

              • Understanding WPF User Interface Events

                • Using Events

                • Chapter 17 Quick Reference

                • Chapter 18: Introducing Generics

                  • The Problem with objects

                  • The Generics Solution

                    • Generics vs. Generalized Classes

                    • Generics and Constraints

                    • Creating a Generic Class

                      • The Theory of Binary Trees

                      • Building a Binary Tree Class by Using Generics

                      • Creating a Generic Method

                        • Defining a Generic Method to Build a Binary Tree

                        • Chapter 18 Quick Reference

                        • Chapter 19: Enumerating Collections

                          • Enumerating the Elements in a Collection

                            • Manually Implementing an Enumerator

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan