Visual Basic 2005 for Programmers (2nd Edition)
4.6. Value Types and Reference Types
Data types in Visual Basic are divided into two categoriesvalue types and reference types. A variable of a value type (such as Integer) simply contains a value of that type. For example, Fig. 4.10 shows an Integer variable named count that contains the value 7. Figure 4.10. Value type variable.
By contrast, a variable of a reference type (sometimes called a reference) contains the memory address where the data referred to by that variable is stored. Such a variable is said to refer to an object in the program. Line 8 of Fig. 4.8 creates a GradeBook object, places it in memory and stores the object's memory address in reference variable gradeBook of type GradeBook as shown in Fig. 4.11. Note that the GradeBook object is shown with its courseNameValue instance variable. Figure 4.11. Reference type variable.
Reference type instance variables (such as gradeBook in Fig. 4.11) are initialized by default to the value Nothing. Except for type String, Visual Basic's primitive types are value typesString is a reference type. For this reason, the String variable courseNameValue is shown in Fig. 4.11 with an empty box representing the variable in memory. A client of an object must use a reference to the object to invoke (i.e., call) the object's methods and access the object's properties. In Fig. 4.8, the statements in Main use variable gradeBook, which contains the GradeBook object's reference, to send messages to the GradeBook object. These messages are calls to methods (like DisplayMessage) or references to properties (like CourseName) that enable the program to interact with GradeBook objects. For example, the statement (in line 20) gradeBook.CourseName = theName ' set the CourseName (invokes Set)
uses gradeBook to set the course name by assigning a value to property CourseName. This sends a message to the GradeBook object to invoke the CourseName property's Set accessor. The message includes as an argument the value (i.e., the value of theName, namely CS101 Introduction to Visual Basic Programming) that CourseName's Set accessor requires to perform its task. The Set accessor uses this information to set the courseNameValue instance variable. In Section 7.11, we discuss value types and reference types in detail. |
Категории