Programming Visual Basic 2008 phần 4 doc

79 388 0
Programming Visual Basic 2008 phần 4 doc

Đ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

216 | Chapter 7: Windows Forms The TaskLibraryItem procedure adjusts the various panels and fields on the display so that the user sees those fields needed to look up library items. Private Sub TaskLibraryItem( ) ' Update the display. AllPanelsInvisible( ) PanelLibraryItem.Visible = True ActLibraryItem.BackColor = SystemColors.Control LabelSelected.Location = New System.Drawing.Point( _ LabelSelected.Left, PicLibraryItem.Top) Me.AcceptButton = ActSearch End Sub The AllPanelsInvisible routine also does some on-screen adjustment. I like to have the existing text in a TextBox field selected when it becomes the active control. Each text control includes a SelectAll method that accomplishes this feat. We’ll call that method during each TextBox control’s Enter event, an event that occurs when a control receives the keyboard input focus. Private Sub SearchText_Enter(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles SearchText.Enter ' Highlight the entire text. SearchText.SelectAll( ) End Sub Figure 7-12. The basic look of the main form Project | 217 Using the mouse to access the different features of the form is good, but I’m a key- board person. To deal with keyboard users like me, the code adds support for fea- ture access using the F2 through F9 keys. Private Sub MainForm_KeyDown(ByVal sender As Object, _ ByVal e As System.Windows.Forms.KeyEventArgs) _ Handles MyBase.KeyDown ' The keys F2 through F9 access the different ' sections of the form. Select Case (e.KeyCode) Case Keys.F2 TaskLibraryItem( ) e.Handled = True Case Keys.F3 TaskPatronRecord( ) e.Handled = True Case Keys.F4 ' Allow form to handle Alt+F4. If (e.Alt = True) Then Me.Close( ) Else TaskHelp( ) End If e.Handled = True Case Keys.F5 TaskCheckOut( ) e.Handled = True Case Keys.F6 TaskCheckIn( ) e.Handled = True Case Keys.F7 TaskAdmin( ) e.Handled = True Case Keys.F8 TaskProcess( ) e.Handled = True Case Keys.F9 TaskReports( ) e.Handled = True End Select End Sub As each keystroke comes into the KeyDown event handler, the Select Case statement examines it. When a matching Case entry is found, the code within the Case block executes. Pressing the F2 key triggers the code in the Case Keys.F2 block. Keys is one of the many built-in enumerations that you can use in your .NET applications. Notice the special code for the F4 key. It allows the Alt-F4 key combination to exit the application, which is the standard key combination for exiting Windows programs. Normally, all keystrokes go to the active control, not to the form. To enable the MainForm.KeyDown event handler, the form’s KeyPreview property must be set to True. Set this property back in the form designer. 218 | Chapter 7: Windows Forms Making the Program Single-Instance The Library Project is designed for use only within a small library; it will run on only a few workstations at a time, perhaps up to 10 at most. And there’s no need to run more than one copy on a single workstation, since each copy includes all the avail- able application features. One of the cool features included with Visual Basic is the ability to create a “single-instance application,” one that enforces the one-at-a-time run policy on each workstation. Although you could create such applications before, it is now enabled with a single mouse click. To make the Library Project a single-instance application, display the project proper- ties’ Application panel, and then select the “Make single instance application” field. When the user tries to start up a second instance, .NET will refuse to carry out the request. Instead, it will trigger the application’s StartupNextInstance event. Any spe- cial handling you wish to perform on a second instance startup will be done in this handler. Like the Startup event handler, the StartupNextInstance handler appears in the ApplicationEvents.vb file. For the Library Project, the only thing we really need to do when the user tries to start a second instance is to make sure the application is displayed front and center, where the user can readily view it. Open the ApplicationEvents.vb file, and add the StartupNextInstance event handler. INSERT SNIPPET Insert Chapter 7, Snippet Item 5. Private Sub MyApplication_StartupNextInstance( _ ByVal sender As Object, _ ByVal e As Microsoft.VisualBasic.ApplicationServices. _ StartupNextInstanceEventArgs) _ Handles Me.StartupNextInstance ' Force the main form to the front. My.Application.MainForm.Activate( ) End Sub That’s all the changes for this chapter. See you on the next page. 219 Chapter 8 CHAPTER 8 Classes and Inheritance8 How many .NET programmers does it take to change a light bulb? None—they call a method on the light bulb object, and it changes itself. Ha, ha, ha! That’s funny, but only if you understand the object-oriented programming (OOP) concepts that are the basic foundation of the .NET system. (Actually, it’s not even that funny if you do under- stand OOP.) Without OOP, it would be difficult to support core features of .NET, such as the central System.Object object, which is the basic foundation of the .NET system. Also, productivity would go way down among Windows developers, who are the basic foundation of the .NET system. Although I briefly mentioned OOP development concepts in Chapter 1 and Chapter 2, it was only to provide some context for other topics of discussion. But in this chapter, I hold back no longer. After a vigorous discussion of general OOP con- cepts, I’ll discuss how you can use these concepts in your .NET code. Object-Oriented Programming Concepts If you’ve read this far into the book, it’s probably OK to let you in on the secret of object-oriented computing. The secret is: it’s all a sham, a hoax, a coverup. That’s right, your computer does not really perform any processing with objects, no matter what their orientation. The CPU in your computer processes data and logic state- ments the old-fashioned way: one step at a time, moving through specific areas in memory as directed by the logic, manipulating individual values and bits according to those same logic statements. It doesn’t see data as collective objects; it sees only bits and bytes. One moment, I’ve just been handed this important news bulletin. It reads, “Don’t be such a geek, Tim. It’s not the computer doing the object-oriented stuff, it’s the pro- grammer.” Oh, sorry about that. But what I said before still stands: the final code as executed by your CPU isn’t any more object-oriented than old MS-DOS code. But object-oriented language compilers provide the illusion that OOP is built into the computer. You design your code and data in the form of objects, and the compiler 220 | Chapter 8: Classes and Inheritance takes it from there. It reorganizes your code and data, adds some extra code to do the simulated-OOP magic, and bundles it all up in an EXE file. You could write any OOP program using ordinary procedural languages, or even assembly language. But applications that focus on data can often be written much more efficiently using OOP development practices. The Object The core of object-oriented programming is, of course, the object. An object is a per- son, place, or thing. Wait a minute, that’s a noun. An object is like a noun. Objects are computer data-and-logic constructs that symbolize real-world entities, such as people, places, or things. You can have objects that represent people, employees, dogs, sea otters, houses, file cabinets, computers, strands of DNA, galaxies, pictures, word processing documents, calculators, office supplies, books, soap opera charac- ters, space invaders, pizza slices, majestic self-amortizing canals, plantations of ripen- ing tea, a few of my favorite things, and sand. Objects provide a convenient software means to describe and manage the data asso- ciated with one of these real-world objects. For instance, if you had a set of objects representing DVDs in your home video collection, the object could manage features of the DVD, such as its title, the actors performing in the content, the length of the video in minutes, whether the DVD was damaged or scratched, its cost, and so on. If you connected your application to the DVD-ROM player in your system, your object could even include a “play” feature that (assuming the DVD was in the drive) would begin to play the movie, possibly from a timed starting position or DVD “chapter.” Objects work well because of their ability to simulate the features of real-world counter- parts through software development means. They do this through the four key attributes of objects: abstraction, encapsulation, inheritance, and polymorphism. Throughout this chapter, the term object usually refers to an instance of something, a specific in-memory use of the defined element, an instance with its own set of data, not just its definition or design. Class refers to the design and source code of the object, comprising the implementation. Abstraction An abstraction indicates an object’s limited view of a real-world object. Like an abstract painting, an abstracted object shows just the basic essentials of the real- world equivalent (see Figure 8-1). Objects can’t perfectly represent real-world counterparts. Instead, they implement data storage and processes on just those elements of the real-world counterpart that are important for the application. Software isn’t the only thing that requires abstrac- tion. Your medical chart at your doctor’s office is an abstraction of your total physi- cal health. When you buy a new house, the house inspector’s report is an abstraction Object-Oriented Programming Concepts | 221 of the actual condition of the building. Even the thermometer in your back yard is an abstraction; it cannot accurately communicate all of the minor temperature varia- tions that exist just around the flask of mercury. Instead, it gathers all the information it can, and communicates a single numeric result. All of these abstract tools record, act on, or communicate just the essential informa- tion they were designed to manage. A software object, in a similar way, only stores, acts on, or communicates essential information about its real-world counterpart. For instance, if you were designing an object that monitored the condition of a building, you might record the following: • Building location and address • Primary construction material (wood, concrete, steel-beam, etc.) • Age (in years) • General condition (from a list of choices) • Inspector notes Although a building would also have color, a number of doors and windows, and a height, these elements may not be important for the application, and therefore would not be part of the abstraction. Those values that are contained within the object are called properties. Any processing rules or calculations contained within the object that act on the properties (or other supplied internal or external data) are known as methods. Taken together, methods and properties make up the members of the object. Figure 8-1. Actually, the one on the left is kind of abstract, too Original Abstract 222 | Chapter 8: Classes and Inheritance Encapsulation The great advantage of software is that a user can perform a lot of complex and time- consuming work quickly and easily. Actually, the software takes care of the speed and the complexity on behalf of the user, and in many cases, the user doesn’t even care how the work is being done. “Those computers are just so baffling; I don’t know and I don’t care how they work as long as they give me the results I need” is a common statement heard in management meetings. And it’s a realistic statement too, since the computer has encapsulated the necessary data and processing logic to accomplish the desired tasks. Encapsulation carries with it the idea of interfaces. Although a computer may con- tain a lot of useful logic and data, if there was no way to interact with that logic or data, the computer would basically be a useless lump of plastic and silicon. Inter- faces provide the means to interact with the internals of an object. An interface pro- vides highly controlled entries and exits into the data and processing routines contained within the object. As a consumer of the object, it’s really irrelevant how the object does its work internally, as long as it produces the results you expect through its publicly exposed interfaces. Using the computer as an example, the various interfaces include (among other things) the keyboard, display, mouse, power connector, USB and 1394 ports, speak- ers, microphone jack, and power button. Often, the things I connect to these inter- faces are also black boxes, encapsulations with well-defined public interfaces. A printer is a mystery to me. How the printer driver can send commands down the USB cable and eventually squirt ink onto 24-pound paper is just inexplicable, but I don’t know and I don’t care how it really works, as long as it does work. Inheritance Inheritance in .NET isn’t like inheritance in real life; no one has to die before it works. But as in real life, inheritance defines a relationship between two different objects. Specifically, it defines how one object is descended from another. The original class in the object relationship is called the base class. It includes vari- ous and sundry interface members, as well as internal implementation details. A derived class is defined using the base class as the starting point. Derived classes inherit the features of the base class. By default, any publicly exposed members of the base class automatically become publicly exposed members of the derived class, including the implementation. A derived class may choose to override one, some, or all of these members, providing its own distinct or supplementary implementation details. Derived classes often provide additional details specific to a subset of the base class. For instance, a base class that defines animals would include interfaces for the com- mon name, Latin species name, number of legs, and other typical properties belonging Object-Oriented Programming Concepts | 223 to all animals. Derived classes would then enhance the features of the base class, but only for a subset of animals. A mammal class might define gestation time for birth- ing young, whereas a parallel avian-derived class could define the diameter of an egg. Both mammal and avian would still retain the name, species name, and leg count properties from the base animal class. An instance of avian would be an animal;an instance of mammal would be an animal. However, an instance of avian would not be a mammal. Also, a generic instance of animal could be considered as an avian only if it was originally defined as an avian. Even though a base and derived class have a relationship, implementation details that are private to the base class are not made available to the derived class. The derived class doesn’t even know that those private members exist. A base class may include protected members that, although hidden from users of the class, are visible to the derived class. Any member defined as public in the base class is available to the derived class, and also to all users of the base class. (Visual Basic defines another level named friend. Members marked as friend are available to all code in the same assembly, but not to code outside the assembly. Public members can be used by code outside the defining assembly.) Examples of inheritance do exist in the real world. A clock is a base object from which an alarm clock derives. The alarm clock exposes the public interfaces of a clock, and adds its own implementation-specific properties and methods. Other examples include a knife and its derived Swiss Army knife, a chair and its derived recliner, and a table and its derived Periodic Table of the Chemical Elements. Polymorphism The concepts introduced so far could be implemented using standard procedural programming languages. Although you can’t do true inheritance in a non-OOP lan- guage such as C, you can simulate it using flag fields: if a flag field named “type” in a non-OOP class-like structure was set to “mammal,” you could enable use of certain mammal-specific fields. There are other ways to simulate these features, and it wouldn’t be too difficult. Polymorphism is a different avian altogether. Polymorphism means “many forms.” Because a derived class can have its own (overridden) version of a base class’s mem- ber, if you treat a mammal object like a generic animal, there could be some confu- sion as to which version of the members should be used, the animal version or the mammal version. Polymorphism takes care of figuring all this out, on an ad hoc basis, while your program is running. Polymorphism makes it possible for any code in your program to treat a derived instance as though it were its base instance. This makes for great coding. If you have a routine that deals with animal objects, you can pass it objects of type animal, mammal,oravian, and it will still work. This type of polymorphism is known as subtyping polymorphism, but who cares what its name is. 224 | Chapter 8: Classes and Inheritance Another variation of polymorphism is overloading. Overloading allows a single class method (forget about derived classes for now) to have multiple forms, but still be considered as a single method. For instance, if you had a house object with a paint method (that would change the color of the house), you could have one paint method that accepted a single color (paint the house all one color) and another paint method that accepted two colors (the main color plus a trim color). When these methods are overloaded in a single class, the compiler determines which version to call based on the data you include in the call to the method. Interfaces and Implementation OOP development differentiates between the public definition of a class, the code written to implement that class, and the resultant in-memory use of that class as an object. It’s similar to how, at a restaurant, you differentiate between a menu, the cooking of your selection, and the actual food that appears at your table: • The description of an item on the menu is (to some extent) its interface; it describes what the real object will expose publicly in terms of taste, smell, and so on. • The method used by the kitchen staff to make the food is the implementation; it’s how the meal is prepared. There may be different implementations by different restaurants for the same menu item. In objects, the implementation is hidden from public view; in a restaurant, food preparation is thankfully hidden from view or no one would ever eat there. • The food you receive from the kitchen is—ta-da!—the object, the actual instance of what the menu described. Many hungry customers may each order the same menu item, and each would receive a distinct instance of the food. OOP in Visual Basic and .NET Conceptually, OOP really isn’t that complex. Since both humans and programmers interact with real-world objects and instances every day, it’s pretty easy to wrap their minds around the idea of programming with objects. But how easy is it to communi- cate these object concepts to the computer through the Visual Basic compiler and the .NET Framework? Can it be done without weekly sessions on a shrink’s comfy sofa? Duh! It’s Visual Basic; of course it’s easy. One reason objects are so easy in .NET is that they have to be. Everything in your .NET program is part of an object, and if everything about .NET was hard, you’d be reading a book on Macintosh development right about now. But it’s not too hard because the Visual Basic implementation of objects parallels the conceptual ideas of objects. OOP in Visual Basic and .NET | 225 Classes Visual Basic uses classes and structures to define objects. I’ll talk about structures a little later in the chapter. The Class keyword starts the definition of a class. Class Superhero ' Class-related code goes here. End Class That’s most of it: the Class keyword, and a name for the class (“Superhero,” in this case). All classes reside in a namespace (discussed way back in Chapter 1). By default, your classes appear in a namespace that is named after your project. You can alter this in the project properties (to set the top-level namespace for your assembly) and with the Namespace statement (to indicate relative namespaces from your assem- bly’s top-level namespace). Namespace GoodGuys Class Superhero End Class End Namespace If your application’s default namespace is WindowsApplication1, the class in this sam- ple code would be identified as WindowsApplication1.GoodGuys.Superhero. You can add any number of classes to a namespace. Classes that use the same name, but that appear in different namespaces, are unrelated. The members of a class appear between the Class and End Class clauses. You can also split a class’s definition into multiple source code files. If you do split up a class like this, at least one of the parts must include the keyword Partial in the definition. Partial Class Superhero As with variable definitions, classes are defined using one of the access modifier key- words: Public, Private, Protected, Friend,orProtected Friend. Flip back to Chapter 6, in the “Variables” section, if you need a refresher course. The .NET Framework Class Libraries (FCLs) are simply loaded with classes and objects, and they are all pretty much defined with this simple keyword: Class. Class Members Calling your class Superhero won’t endow it with any special powers if you don’t add any members to the class. All class members must appear between the Class and End Class boundaries, although if you use the Partial feature to break up your class, you can sprinkle the members among the different class parts in any way you wish. You can include 11 different kinds of members in your Visual Basic classes. Other books or documents may give you a different number, but they’re wrong, at least if they organize things the way I do here: [...]... appears in the Microsoft.VisualBasic namespace—must be spurned in favor of class library alternatives I find it to be a preference choice, but you may encounter just such a person insisting that your code is substandard You can read my views about such tactics in Chapter 26 If you plan to develop Visual Basic code that targets Microsoft’s Silverlight platform, avoiding Microsoft.VisualBasic can bring about... _ MsgBoxStyle.YesNoCancel Or MsgBoxStyle.Question, _ "Click Something") Related Issues | 241 Figure 8-2 Communicating an important message The MsgBox function is considered to be an intrinsic part of the language But as a member of the Microsoft.VisualBasic namespace, it’s generally used only within the Visual Basic language If you were to do some NET coding in C#, you would normally opt instead for... Although I’ve used it on practically every page of this book so far, I have never formally introduced you to the MsgBox method Part of the Microsoft.VisualBasic namespace, MsgBox is a carryover from the MsgBox function in the original release of Visual Basic It displays a simple message window, including a selection of response buttons and an optional icon As a function, it returns a code indicating... As Color, _ ByVal coats As Integer) ' - Possibly paint with many coats, of paint ' that is, not of fabric End Sub End Class OOP in Visual Basic and NET | 229 When you call the PaintHouse method, you must pass arguments that match one of the overloaded versions Visual Basic determines which version to use based on the argument signature If you pass the wrong type or number of arguments, the program... Partial classes are especially common in code created by code generators Visual Studio is, in part, a code generator; as you drag-and-drop controls on your form, it generates code for you in a partial Form class In such cases, partial classes have two authors: the automated generator and you Partial methods, new in Visual Basic 2008, are also used by code generators, although you are free to employ... purposes Anything you can do to eliminate dependencies on external assemblies such as Microsoft.VisualBasic will help speed your program along Using DoEvents Programs are designed to do a lot of thinking, and sometimes they think so much, they pretty much lock up the computer This is especially true of Visual Basic methods that perform a lot of database-heavy transactions, one right after another The... important to differentiate between base and derived code, and this is the way to do it OOP in Visual Basic and NET | 233 The MyBase keyword references elements of the base class from which the current class derives It references only the closest base class; if you have a class named Class5 that derives from Class4, which in turn derives from Class3, which derives from Class2, which derives from Class1,... “Get to the point, Tim,” you say The point is that if you never write the second half of a partial method, the Visual Basic compiler will leave out both halves, generating code as though the unimplemented half was never autogenerated in the first place So, that earlier Animal class becomes: 240 | Chapter 8: Classes and Inheritance Partial Class Animal Public Sub Move( ) ' - Interesting movement code,... class or module, nor can you use a module as a base for any other type Modules are a carryover from pre-.NET versions of Visual Basic, which included “Modules” for all non-Form code Friend Module GenericDataAndCode ' - Application-global constant Public Const AllDigits As String = "012 345 6789" ' - Application-global function Public Function GetEmbeddedDigits( _ ByVal sourceString As String) As String... everything And refreshing the display wouldn’t do much to enable the “Cancel” button that you want your user to click to abort all that lovely data processing To make life easier, Visual Basic includes a DoEvents method 242 | Chapter 8: Classes and Inheritance When this method is called, the current method’s code pauses temporarily, and messages in the thread’s incoming message queue are processed, . it’s not too hard because the Visual Basic implementation of objects parallels the conceptual ideas of objects. OOP in Visual Basic and .NET | 225 Classes Visual Basic uses classes and structures. creating class instances. Step four: cha-cha-cha. Visual Basic uses the New keyword to create instances of your custom classes. OOP in Visual Basic and .NET | 233 Dim myPet As Animal = New Animal '. parts in any way you wish. You can include 11 different kinds of members in your Visual Basic classes. Other books or documents may give you a different number, but they’re wrong, at least if they

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

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

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

Tài liệu liên quan