Visual Basic .NET How to Program, Second ... - Pearsoncmg.com

336 downloads 202 Views 541KB Size Report
To view all the Deitel products and services available, visit the Deitel Kiosk on. InformIT at ... such as the .NET Framework, must be imported into a Visual Basic .
informITheaderpage.fm Page 39 Friday, July 19, 2002 9:50 AM

Ordering Information: Visual Basic .NET How to Program, Second Edition The Visual Basic .NET Training Course, Second Edition •

View the complete Table of Contents



Read the Preface



Download the Code Examples

To view all the Deitel products and services available, visit the Deitel Kiosk on InformIT at www.informIT.com/deitel. To follow the Deitel publishing program, sign-up now for the DEITEL™ BUZZ ONLINE e-mail newsletter at www.deitel.com/newsletter/subscribeinformIT.html.

To learn more about our Visual Basic .NET programming courses or any other Deitel instructor-led corporate training courses that can be delivered at your location, visit www.deitel.com/training, contact our Director of Corporate Training Programs at (978) 461-5880 or e-mail: [email protected]. Note from the Authors: This article is an excerpt from Chapter 8, Section 8.15 of Visual Basic .NET How to Program, 2/E. This article introduces creating class libraries in Visual Basic .NET, which serve as prepackaged code for other applications. In the article we provide an example of creating a class library and using the resulting assembly created when the class library is compiled. Readers should be familiar with Visual Basic .NET syntax, as well as objects, classes and modules. The code examples included in this article show readers programming examples using the DEITEL™ signature LIVE-CODE™ Approach, which presents all concepts in the context of complete working programs followed by the screen shots of the actual inputs and outputs.

vbhtp2_08.fm Page 1 Friday, July 19, 2002 9:21 AM

Chapter 8

Object-Based Programming

1

8.15 Namespaces and Assemblies As we have seen in almost every example in the text, classes from preexisting libraries, such as the .NET Framework, must be imported into a Visual Basic .NET program by including a reference to those libraries. Remember that each class in the Framework Class Library belongs to a specific namespace. This preexisting code provides a mechanism that facilitates software reuse. When appropriate, programmers should concentrate on making the software components they create reusable. However, doing so often results in naming collisions, which occur when the same name is used for two classes in the same namespace, for two methods in the same class, etc. Namespaces help minimize this problem by providing a convention for unique class names. No two classes in a given namespace can have the same name, but different namespaces can contain classes with the same name. With millions of people writing Visual Basic .NET programs, the names that one programmer chooses for classes will likely conflict with the names that other programmers choose for their classes. Figure 8.17, which provides the code for class CEmployee3, demonstrates the creation of a reusable class library. Notice that we have declared class CEmployee3 as a Public class. When other projects make use of a class library, only Public classes are accessible—thus, if we did not declare CEmployee3 as Public, other projects could not use it. We demonstrate momentarily how to package class CEmployee3 into EmployeeLibrary.dll—the dynamic link library that we create for reuse with other systems. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

' Fig. 8.17: CEmployee3.vb ' Class CEmployee3 uses Shared variable. Public Class CEmployee3 Inherits Object

Fig. 8.17

Private mFirstName As String Private mLastName As String ' number of objects in memory Private Shared mCount As Integer ' CEmployee3 constructor Public Sub New(ByVal firstNameValue As String, _ ByVal lastNameValue As String) mFirstName = firstNameValue mLastName = lastNameValue mCount += 1 ' increment shared count of employees Console.WriteLine _ ("Employee object constructor: " & mFirstName & _ " " & mLastName) End Sub ' New

CEmployee3 class to store in class library. (Part 1 of 2.) © Copyright 2002 Prentice Hall. All Rights Reserved.

vbhtp2_08.fm Page 2 Friday, July 19, 2002 9:21 AM

2

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61

Object-Based Programming

Chapter 8

' finalizer method decrements Shared count of employees Protected Overrides Sub Finalize() mCount -= 1 ' decrement mCount, resulting in one fewer object Console.WriteLine _ ("Employee object finalizer: " & mFirstName & _ " " & mLastName & "; count = " & mCount) End Sub ' Finalize ' return first name Public ReadOnly Property FirstName() As String Get Return mFirstName End Get End Property ' FirstName ' return last name Public ReadOnly Property LastName() As String Get Return mLastName End Get End Property ' LastName ' property Count Public ReadOnly Shared Property Count() As Integer Get Return mCount End Get End Property ' Count End Class ' CEmployee3

Fig. 8.17

CEmployee3 class to store in class library. (Part 2 of 2.)

We now describe how to create a class library that includes class CEmployee3: 1. Create a class library project. Select File > New > Project... to display the New Project dialog. Select Visual Basic Projects from the Project Types: pane, then select Class Library from the Templates: pane. Name the project EmployeeLibrary, and choose a directory in which you would like the project to be located (you many choose any directory you wish). A class library is created, as shown in Fig. 8.18. There are two important points to note about the class library’s code. The first is that there is no Main method. This indicates that a class library is not an executable program. Class libraries are software components that are loaded and used (and reused) by executable programs. A class library is not designed as a stand-alone application—rather, it is designed to be used by running programs. The second key point is that Class1 is a Public class, so that it is accessible to other projects (Fig. 8.18). © Copyright 2002 Prentice Hall. All Rights Reserved.

vbhtp2_08.fm Page 3 Friday, July 19, 2002 9:21 AM

Chapter 8

Object-Based Programming

3

2. In the Solution Explorer, rename Class1.vb to CEmployee3.vb (rightclick Class1.vb and select Rename). Replace the following code generated by the development environment: Public Class Class1 End Class

with the entire code listing from class CEmployee3 (Fig. 8.17). Common Programming Error 8.14 Attempting to compile code that contains naming collisions generates a syntax error.

8.14

3. Select Build > Build Solution to compile the code. Remember that this code is not executable. If the programmer attempts to execute the class library by selecting Debug > Start Without Debugging, Visual Studio displays an error message. When the class library is compiled successfully, an assembly is created. This assembly is located in the project’s bin directory, and by default is named EmployeeLibrary.dll. The assembly file contains class CEmployee3, which other modules, classes and systems can use. Assembly files, which have file extensions .dll and .exe, are at the core of Visual Basic .NET application development. The Windows operating system uses executable files (.exe) to run applications and library files (.dll, or dynamic link library) to create code libraries.

Fig. 8.18

Simple class library project. © Copyright 2002 Prentice Hall. All Rights Reserved.

vbhtp2_08.fm Page 4 Friday, July 19, 2002 9:21 AM

4

Object-Based Programming

Chapter 8

Portability Tip 8.1 Focus on creating unique namespace names to avoid naming collisions. This is especially helpful when using someone else’s code (or when someone else uses your code).

8.0

Module modAssemblyTest (Fig. 8.8) demonstrates the use of the assembly file in a running application. The module employs class CEmployee3 in EmployeeLibrary.dll to create and mark two CEmployee3 for garbage collection. A reference to the assembly is created by selecting Project > Add Reference. Using the Browse button, select EmployeeLibrary.dll (located in the bin directory of our EmployeeLibrary project), then click OK to add the resource to the project. Once the reference has been added, we use keyword Imports followed by the namespace’s name (EmployeeLibrary) to inform the compiler that we are using classes from this namespace (line 4). 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37

' Fig. 8.19: AssemblyTest.vb ' Demonstrates assembly files and namespaces. Imports EmployeeLibrary ' contains class CEmployee3 Module modAssemblyTest Public Sub Main() Dim output As String Console.WriteLine("Employees before instantiation: " & _ CEmployee3.Count) Dim employee1 As CEmployee3 = _ New CEmployee3("Susan", "Baker") Dim employee2 As CEmployee3 = _ New CEmployee3("Bob", "Jones") ' output of employee after instantiation Console.WriteLine(vbCrLf & "Employees after instantiation:" _ & vbCrLf & "via Employee.Count: " & CEmployee3.Count) ' display name of first and second employee Console.WriteLine(vbCrLf & "Employees 1: " & _ employee1.FirstName & " " & employee1.LastName & _ vbCrLf & "Employee 2: " & employee2.FirstName & " " & _ employee2.LastName) ' mark employee1 and employee2 for garbage collection employee1 = Nothing employee2 = Nothing System.GC.Collect() ' request garbage collection End Sub ' Main End Module ' modAssemblyTest

Fig. 8.8

Module modAssemblyTest references EmployeeLibrary.dll. (Part 1 of 2.) © Copyright 2002 Prentice Hall. All Rights Reserved.

vbhtp2_08.fm Page 5 Friday, July 19, 2002 9:21 AM

Chapter 8

Object-Based Programming

Employees before instantiation: 0 Employee object constructor: Susan Baker Employee object constructor: Bob Jones Employees after instantiation: via Employee.Count: 2 Employees 1: Susan Baker Employee 2: Bob Jones Employee object finalizer: Bob Jones; count = 1 Employee object finalizer: Susan Baker; count = 0 Fig. 8.8

Module modAssemblyTest references EmployeeLibrary.dll. (Part 2 of 2.)

© Copyright 2002 Prentice Hall. All Rights Reserved.

5