Programming Visual Basic 2008 phần 2 pdf

79 285 0
Programming Visual Basic 2008 phần 2 pdf

Đ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

58 | Chapter 2: Introducing Visual Basic Subroutines Subroutines begin with a Sub declaration statement and end with an End Sub state- ment. All of your subroutine’s logic appears in between these two mighty jaws. 01 Sub ShowIngredients(ByVal gender As Char) 02 Dim theMessage As String = "Unknown." 03 If (gender = "M"c) Then 04 theMessage = "Snips and snails and puppy dog tails." 05 ElseIf (gender = "F"c) Then 06 theMessage = "Sugar and spice and everything nice." 07 End If 08 MsgBox(theMessage) 09 End Sub Line 01 shows the subroutine’s declaration line in its simplest form; throughout the book, you will find that there are additional keywords that decorate procedure decla- rations to change their behavior. The statement begins with the Sub keyword (for subroutine), followed by the name of the procedure, ShowIngredients. The parentheses following this name contain the subroutine’s parameters. Parame- ters allow another block of code that will use this procedure to pass data into the procedure, and optionally receive data back. You can include any number of parame- ters in the subroutine definition; simply separate them by commas. Each parameter specifies the name as it will be used in the procedure ( gender in the sample) and its data type ( Char). The arguments are treated as declared variables within the proce- dure, as is done with gender on lines 03 and 05. The values supplied by the calling code are known as arguments. All arguments are passed by value or by reference. In the sample code, the argument passed into gender will be passed by value, as specified through the ByVal keyword. The related ByRef keyword indicates an argument to be passed by reference. If you don’t include either keyword, ByVal is assumed. This passing method impacts whether changes made to the argument within the local procedure are propagated back to the calling code. However, the ability to update the original data is also influenced by whether the data is a value type or a reference type. Table 2-3 indicates the behavior for each com- bination of passing method and data type. Table 2-3. Updating data, the .NET way Passing method Data type Behavior ByVal Value type Changes made to the local version of the argument have no impact on the original version. ByVal Reference type Changes made to members of the data object immediately impact the original data object. However, the object itself cannot be changed or replaced with a completely new data object. Creating Your Own Procedures | 59 In most cases, if you are interested in modifying the value of a parameter and having the changes return to the caller, use ByRef; otherwise, use ByVal. Lines 02 through 08 in the sample code comprise the body of the procedure, where all your logic appears. Any variables to be used solely in the routine are also defined here, as with the theMessage variable on line 02. The subroutine always concludes with an End Sub statement. Functions The syntax of a function differs only slightly from subroutines, to support a return value. 01 Function IsPrime(ByVal source As Long) As Boolean 02 ' Determine whether source is a prime number. 03 Dim testValue As Long 04 If (source < 2) Then 05 Return False 06 ElseIf (source > 2) Then 07 For testValue = 2 To source \ 2& 08 If ((source Mod testValue) = 0) Then 09 Return False 10 End If 11 Next testValue 12 End If 13 Return True 14 End Function As with subroutines, the function’s declaration line appears first (line 01), followed by the body (lines 02 through 13) and the closing End Function statement (line 14). The declaration line includes an extra data type definition after the parameter list. This is the data type of the final value to be returned to the calling code. Use this return value in the calling code just like any other value or variable. For example, the following line calls the IsPrime function and stores its Boolean result in a variable: primeResult = IsPrime(23) To indicate the value to return, use the Return statement (described later in the chap- ter). The sample code does this on lines 05, 09, and 13. (An older VB 6.0 syntax that lets you assign the return value to the name of the function still works.) ByRef Value type Changes made to the local version are returned to the calling procedure, and permanently impact the original data value. ByRef Reference type Changes made to either the data object or its members are also changed in the original. It is possible to fully replace the object sent into the procedure. Table 2-3. Updating data, the .NET way (continued) Passing method Data type Behavior 60 | Chapter 2: Introducing Visual Basic Properties A little earlier I mentioned fields, which are variables or constants that appear within a class, but outside any procedure definition. 01 Class PercentRange 02 Public Percent As Integer 03 End Class Properties are similar to fields; they are used like class-level variables or constants. But they are programmed like functions, accepting parameters, having return values, and including as much logic as you require. Properties are often used to protect private class data with logic that weeds out inap- propriate values. The following class defines a single property that provides access to the hidden related field: 01 Class PercentRange 02 ' Stores a percent from 0 to 100 only. 03 Private savedPercent As Integer 04 Public Property Percent( ) As Integer 05 Get 06 Return savedPercent 07 End Get 08 Set(ByVal value As Integer) 09 If (value < 0) Then 10 savedPercent = 0 11 ElseIf (value > 100) Then 12 savedPercent = 100 13 Else 14 savedPercent = value 15 End If 16 End Set 17 End Property 18 End Class The Percent property (lines 04 to 17) protects access to the savedPercent field (line 03), correcting any caller-supplied values that exceed the 0 to 100 range. Properties include separate assignment and retrieval components, also called accessors. The Get accessor (lines 05 to 07) returns the property’s monitored value to the caller. The Set accessor (lines 08 to 16) lets the caller modify the value of the property. The property declaration statement (line 04) includes a data type that matches the data type passed into the Set accessor (line 08). This is the data type of the value set or retrieved by the caller. To use this sample Percent property, create an instance of the PercentRange class, and then use the property: Dim activePercent As New PercentRange activePercent.Percent = 107 ' An out-of-range Integer MsgBox(activePercent.Percent) ' Displays "100", not "107" Other Flow Control Features | 61 You can create read-only or write-only properties by including the ReadOnly or WriteOnly keyword just before the Property keyword in the declaration statement (line 04), and leaving out the unneeded accessor. Properties do not need to be tied to fields. You can use properties to get and set any type of value, and store it or act upon it in any manner you wish. Where to Put Your Procedures Back in the good ol’ days of Visual Basic 6.0, procedures could appear just about anywhere in your source code files. You would open a source file, type a function, and go; it was that easy. With the move to .NET, all Visual Basic procedures must now appear within a defined class (or a structure or module). Class Employee Sub StartVacation( ) End Sub Function TotalVacationTaken( ) As Double End Function End Class When you create instances of your class later in code, the methods can be called directly through the object instance. Dim executive As New Employee executive.StartVacation( ) Chapter 8 shows you how to use and build classes. Other Flow Control Features The loops and conditional statements available in Visual Basic let you reroute your code based on data. The language includes a few other statements that let you con- trol the action in a more direct manner. The GoTo Statement The GoTo statement lets you jump immediately to some other location within the cur- rent procedure. The destination of a jump is always a line label, a named line posi- tion in the current procedure. All line labels appear at the start of a logical line, and end with a colon. PromptUser: GetValuesFromUser(numerator, denominator) If (denominator = 0) Then GoTo PromptUser quotient = numerator / denominator 62 | Chapter 2: Introducing Visual Basic In this sample, the GoTo statement jumps back to the PromptUser label when the code detects invalid data. Processing continues with the line immediately following the PromptUser label. You can’t use the same label name twice in the same procedure, although you can reuse label names in different procedures. If you want, include another logic statement on the same line as your label, right after the colon, although your code will be somewhat easier to read if you keep labels on their own lines. LabelAlone: MsgBox("It's all alone.") LabelAndCode: MsgBox("Together again.") It’s all right to include as many labels in your code as you need, but the GoTo state- ment is one of those elements of Visual Basic that is monitored closely by pesky international software agencies, such as the International Committee to Keep GoTo Always Gone (ICK-GAG). That group also scans computer books looking for derogatory references to its organization name—not that it would find anything like that in this book. But its core issue is that overuse of GoTo statements can lead to spaghetti code, such as the following: Dim importantMessage As String = "Do" GoTo Step2 Step6: importantMessage &= "AG!" GoTo Step7 Step3: importantMessage &= "wit" GoTo Step4 Step2: importantMessage &= "wn " GoTo Step3 Step5: importantMessage &= "CK-G" GoTo Step6 Step4: importantMessage &= "h I" GoTo Step5 Step7: MsgBox(importantMessage) Some people say that such code is hard to read. Others call it job security. No mat- ter what you call it, it does make code very hard to maintain and review. You should probably keep an eye on your use of GoTo statements; if you don’t, someone else might. Visual Basic itself places some limits on the use of GoTo. You cannot jump into or out of certain multiline statements that would result in improperly initialized code or data values. For instance, you cannot jump into the middle of a For Next state- ment from outside the statement, since the loop counter variable and the starting and ending ranges would not be properly initialized. ' This GoTo statement will fail. GoTo InsideTheLoop For counter = 1 to 10 InsideTheLoop: MsgBox("Loop number: " & counter) Next counter Other Flow Control Features | 63 However, once you are inside the loop, you can jump to line labels that also appear in the loop, and it’s acceptable to jump out of the loop using GoTo. Some other multi- line structures impose similar restrictions. The Return Statement Not only can you jump around within a procedure using GoTo, but you can also jump right out of a procedure anytime you want using the Return statement. Normally, a procedure exits when processing reaches the last line of code in the procedure; pro- cessing then continues with the code that called the procedure. The Return state- ment provides a way to exit the procedure before reaching the end. In subroutines, the Return statement appears by itself as a standalone statement: Return In functions, the statement must include the value to be returned to the calling code: a variable, a literal, or an expression that must match the specified return value data type of the function. Return 25 Pre NET releases of Visual Basic used an Exit statement to immediately leave a pro- cedure. These are still supported in .NET. There are three variations: Exit Sub Exits a subroutine Exit Function Exits a function Exit Property Exits a property When exiting from a function, the Exit Function statement does not include a way to specify a return value. You must set the return value separately by assigning the return value to the name of the function. Function SafeDivide(ByVal numerator As Double, _ ByVal denominator As Double) As Double ' The "#" sign makes a number a Double. If (denominator = 0#) Then ' Return 0 on invalid division. SafeDivide = 0# Exit Function End If Return numerator / denominator End Function 64 | Chapter 2: Introducing Visual Basic The End and Stop Statements The End and Stop statements bring an immediate halt to your Visual Basic applica- tion. The End statement exits your program immediately, aborting all further code and data processing (although certain acquired resources are cleaned up). The Stop statement suspends processing only when you are running your applica- tion within a debugger, such as the Visual Studio development environment. Stop returns control to the environment, allowing the developer to examine and possibly alter data and code before continuing on with the program. If a Stop is encountered in a standalone application running outside the debugger, it prompts the user to debug the application using any debugger installed on the workstation. Needless to say, the user will not be amused. Events and Event Handlers Visual Basic is an event-driven language. This is especially true of programs written to run on the Windows desktop. After some important initialization, the user is gener- ally in control of all actions in the program. Who knows what the crazy user will do. He might click here. She might type there. It could be all mayhem and bedlam. But whatever the user does, your program will learn about it through events. Since the first days of Windows, desktop programs have used a message pump to communicate user and system actions to your code. Mouse and keyboard input, system-generated actions, and other notifications from external sources flow into a program’s common message queue. The message pump draws these messages out one by one, examines them, and feeds them to the appropriate areas of your code. In traditional Windows programming, you craft the message pump yourself, includ- ing code that makes direct calls to event-handling procedures based on the message type. In a Visual Basic program (both in .NET and earlier), the language provides the message pump for you. It analyzes the messages as they are pumped out of the mes- sage queue, and directs them to the appropriate code. In .NET, this code appears within classes. Once a class has a chance to analyze the message, it can generate an event, which is ultimately processed by an event handler, a subroutine you write to respond to the action. This calling of the event handler is known as firing an event. So, there are two parts of an event: (1) some code that decides to fire the event; and (2) an event handler that responds to the fired event. Events are really just indirect calls to a procedure. Instead of having the main code call another subroutine directly, it asks .NET to call the other subroutine for it, pass- ing specific arguments that the calling code may wish to include. So, why would you want to do this instead of just making the subroutine call directly? For one thing, this indirect method lets you add event handlers long after the initial event-firing code was written. This is good, since the event-firing code may be in a third-party assem- bly that was written years ago. A second benefit is that one event can target multiple Events and Event Handlers | 65 event handlers. When the event fires, each event handler will be called, and each can perform any custom logic found in the handler subroutine. The code that fires the event passes event-specific data to the target event handler(s) through the handler’s parameter list. For the indirect subroutine call to work, the event handler needs to contain the correct number of arguments, in the right order, each of a specific and expected data type. The Event statement defines this contract between the event and the handler. Public Event SalaryChanged(ByVal NewSalary As Decimal) This Event statement defines an event named SalaryChanged with a single argument, a Decimal value. Any event handler wishing to monitor the event must match this argument signature. Sub EmployeePayChanged(ByVal updatedSalary As Decimal) Events can occur for any reason you deem necessary; they need not be tied to user or system actions. In this sample class, an event fires each time a change is made to the employee’s salary. The RaiseEvent statement performs the actual firing of the event, specifying the name of the event to fire, and a set of arguments in parentheses. Public Class Employee Public Name As String Private currentSalary As Decimal Public Property Salary( ) As Decimal Get Return currentSalary End Get Set(ByVal value As Decimal) currentSalary = value RaiseEvent SalaryChanged(currentSalary) End Set End Property Public Event SalaryChanged(ByVal NewSalary As Decimal) End Class The event handlers are not added directly to the class. Instead, they are attached to an instance of the class. The instance, declared as a class field, must be defined using the special WithEvents keyword, which tells Visual Basic that this instance will pro- cess events. Public WithEvents MonitoredEmployee As Employee Event handlers are ordinary subroutines, but they include the Handles keyword to indicate which event is being handled. Private Sub EmployeePayChanged( _ ByVal updatedSalary As Decimal) _ Handles MonitoredEmployee.SalaryChanged MsgBox("The new salary for " & _ MonitoredEmployee.Name & " is " & updatedSalary) End Sub 66 | Chapter 2: Introducing Visual Basic All that is needed is something to kick off the action. Public Sub HireFred( ) MonitoredEmployee = New Employee MonitoredEmployee.Name = "Fred" MonitoredEmployee.Salary = 50000 ' Triggers event End Sub When the salary is set, the Employee class’s Salary property fires the SalaryChanged event using the Visual Basic RaiseEvent command. This generates a call to the EmployeePayChanged event handler, which finally displays the message. The events built into the Windows Forms classes in .NET work just like this, but instead of watching with me for a salary increase, they are watching for mouse clicks and keyboard clacks. All of these system events use a common argument signature. Event EventName(ByVal sender As System.Object, _ ByVal e As System.EventArgs) The sender argument identifies the instance of the object that is firing the event, in case the caller needs to examine its members. The e argument is an object that lets the caller send event-specific data to the handler through a single class instance. The System.EventArgs class doesn’t have much in the way of members, but many events use a substitute class that is derived from System.EventArgs. As we pass through the chapters of this book, there will be no end to the number of event examples you will see and experience. I will save the more involved and inter- esting samples until then. Namespaces Classes, structures, modules, enumerations, interfaces, and delegates—the major .NET types—don’t just float around in the code of your application. They must all be grouped and managed into namespaces. As described in Chapter 1, namespaces pro- vide a hierarchy for your types, sort of a tree-shaped condominium where each type has a home. Some of those homes (or nodes), such as System, get pretty crowded with all those type families living there. Others, such as System.Timers, may have only a few types dwelling in their ample abodes. But every type must live in the hier- archy; none of the types is adventurous enough to strike out on its own and build a ranch house. At the very root of the hierarchy is Global, not a node itself, but a Visual Basic key- word that indicates the root of all roots. You can include Global when referencing your namespaces, but its use is required only when leaving it out would cause confu- sion between two namespace branches. Namespaces | 67 Directly under Global are the few top-level namespaces, including System and Microsoft. Each top-level namespace contains subordinate namespaces, and each of those can contain additional third-level namespaces, and so on. Namespace nodes are referenced relative to one another using a “dot” notation. System.Windows.Forms This specifies the third-level Forms namespace. You could also have typed: Global.System.Windows.Forms which means the same thing. Relative namespaces are also supported: Forms However, to use relative namespaces, you must tell your Visual Basic code to expect them. There are so many namespaces out there, and there may be several Forms namespaces somewhere in the hierarchy. Referencing Namespaces Before namespaces can be used in your code, they must be referenced and optionally imported. Referencing a namespace identifies the DLL assembly file that contains that namespace’s types. Perform both of these actions through the References tab of each project’s Properties form (see Figure 2-3). Figure 2-3. References and imports for a project [...]... through the Visual Studio menus, select Edit ➝ IntelliSense ➝ Insert Snippet The equivalent keyboard sequence is Ctrl-K, Ctrl-X Or type a question mark (?) anywhere in the source code, followed by pressing the Tab key Any of these methods displays the first level of snippets (see Figure 2- 4) Figure 2- 4 Snip, snip, snip Project | 71 From the snippet list, select Programming Visual Basic 20 08, and then... WindowsApplication1.WorkArea.BasicStuff.BusyData: Namespace WorkArea.BasicStuff Class BusyData End Class End Namespace You can include as many Namespace statements in your code as needed Nesting of namespaces is also supported: Namespace WorkArea Namespace BasicStuff Class BusyData End Class End Namespace End Namespace The My Namespace Visual Basic 20 05 introduced a new “My” top-level namespace, designed to simplify common programming. .. splashed all over the screen with a simple yet powerful call to the MsgBox function That’s it for the sample code Now it’s time to roll up your sleeves and embark on a full Visual Basic 20 08 project 74 | Chapter 2: Introducing Visual Basic Chapter 3 CHAPTER 3 Introducing the Project 3 You’re sitting in your office, surfing the I mean reading up on the latest technology issues most pressing to software... and lowercase are handled independently 72 | Chapter 2: Introducing Visual Basic The ReportMessage method fires the MessageDecoded event, sending the previously decoded message to the event as an argument So, where is this event handler? It’s attached to an instance of SayHello that will be added to the Form1 class INSERT SNIPPET Insert Chapter 2, Snippet Item 2 Private WithEvents HelloDecoder As HelloStuff.SayHello... adequate project acceptance by the user Page 1 Project Agreement | 91 • The library application This Visual Basic 20 08 application will be installed on each workstation within the library, and will include both patron and administrative features • The library database This database, stored in SQL Server 20 05, will manage all inventory, patron, and transaction data for the library • Documentation The developer... conclusion You may feel that it went by all too fast; you may feel that you didn’t really learn how to write Visual Basic programs; you may feel that a mild sedative would be right just about now But don’t fret This chapter served as an introduction to the syntax and major features of Visual Basic Now begins the deeper training As we start this book’s main focus—the Library Project—you will encounter... programs that I felt were too large for a particular system So, when I went to work on Visual Basic, I brought to my projects some of this apprehension I tried to make my programs easy to use, but I also held back on the number of forms I would add to my projects It wasn’t an irrational fear; the original versions of Visual Basic did impose limits on code size, the number of unique variable names, and the... project-specific requirements, and includes a typical estimate of project costs For demonstration purposes, I have used an hourly rate of $25 .00 90 | Chapter 3: Introducing the Project Project Agreement Project Name: Library User: The ACME Library Date: February 27 , 20 08 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This project agreement defines a project to be performed by the developer for the user... Chapter 2 (Before) Code project, either through the New Project templates or by accessing the project directly from the installation directory To see the code in its final form, load Chapter 2 (After) Code instead Each chapter’s sample code includes a “Before” and “After” version The “After” version represents the code as it will look when all the changes in that chapter’s 70 | Chapter 2: Introducing Visual. .. long namespaces over and over again, Visual Basic includes an imports feature Imports are namespace-specific; once a namespace has been imported, you can access any of the types in that namespace without specifying the namespace name If you import the System.Windows.Forms namespace, you only have to type “Form” to access the Form class The bottom half of Figure 2- 3 shows how to set these imports through . snippets (see Figure 2- 4). Figure 2- 4. Snip, snip, snip 72 | Chapter 2: Introducing Visual Basic From the snippet list, select Programming Visual Basic 20 08, and then select Chapter 2. A list of the. denominator End Function 64 | Chapter 2: Introducing Visual Basic The End and Stop Statements The End and Stop statements bring an immediate halt to your Visual Basic applica- tion. The End statement. tab of each project’s Properties form (see Figure 2- 3). Figure 2- 3. References and imports for a project 68 | Chapter 2: Introducing Visual Basic Actually, you are not referencing the namespaces

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

Từ khóa liên quan

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

Tài liệu liên quan