一、主模块代码:
'Fig.4.16:GradeBookTest.vb 'Create and manipulate a GradeBook object;illustrate validation Module GradeBookTest 'Main begins program execution Sub Main() 'creat GradeBook object Dim gradeBook1 As New GradeBook("CS101 Introduction to Visual Basic Programming") '这里的对象自带了括号和参数,GradeBook类中必须有New类的构造函数 Dim gradeBook2 As New GradeBook("CS102 Data Structures") '不然的话运行会错误,并提示Public Sub New()参数太多 'display each GradeBook's course name(by invoking Get) Console.WriteLine("gradeBook1's initial course name is:" & gradeBook1.CourseName) Console.WriteLine("gradeBook2's initial course name is:" & gradeBook2.CourseName) Console.WriteLine() 'place in gradeBook's course name a valid-length String gradeBook1.CourseName = "CS101 VB Programming" 'display each GradeBook's course name (by invoking Get) Console.WriteLine("gradeBook1 course name is:" & gradebook1.CourseName) Console.WriteLine("gradeBook2 course name is:" & gradeBook2.CourseName) Console.ReadKey() End Sub 'Main End Module 'GradeBookTest
二、类模块代码
'Fig. 4.15:GradeBook.vb 'GradeBook class with a property that performs validation. Public Class GradeBook Private courseNameValue As String 'course name for this GradeBook 'constructor initializes course name with String supplied as argument Public Sub New(ByVal name As String) '|--关键字New调用类的构造函数,执行初始化任务,构造函数名称必须是New-| CourseName = name '|--构造函数:类名+括号;这里括号中的形参就是主模块中类对象中的实参--| End Sub '|--若主模块中创建一个类对象没有带括号,这里也可以不显式包含构造函数-| ''''''''''''''''''''''''''''''''''''''''''|--把name直接赋值给CourseName就相当于执行了CourseName属性-----------| 'property that gets and sets the course name;the Set accessor 'ensures that the course name has at most 25 characters. Public Property CourseName() As String Get 'retrieve courseNameValue Return courseNameValue End Get Set(ByVal value As String) 'set courseNameValue If value.Length <= 25 Then courseNameValue = value End If If value.Length > 25 Then courseNameValue = value.Substring(0, 25) Console.WriteLine("Name""" & value & """exceeds maximum length (25).") Console.WriteLine("Limiting course name to first 25 characters." & vbNewLine) End If End Set End Property 'CourseName 'display a welcome message to the GradeBook user Public Sub DisplayMessage() 'use property CourseName to display the 'name of the course this GradeBook represents Console.WriteLine("Welcome to the grade book for" & vbNewLine & CourseName & "!") End Sub 'DisplayMessage End Class 'GradeBook
三、运行结果
注:这个简单的例子充分体现了类模块中属性访问符Set对数据进行验证的优点和威力。
来源:Visual Basic 2008 How To Program P107