活代码LINQ——02

复习基础——属性与实例变量

'Fig. 4.8:GradeBookTest.vb
'Create and manipulate a GradeBook object.
Module GradeBookTest
    'Main begins program execution
    Sub Main()
        'line 8 creates a GrateBook object that is referenced by
        'variable gradeBook of type GradeBook
        Dim gradeBook As New GradeBook

        'display initial value of property CourseName(invokes Get:调用Get访问符)
        Console.WriteLine("Initial course name is:" & gradeBook.CourseName & vbNewLine)

        'prompt for course name
        Console.WriteLine("Please enter the course name:")

        'read course name
        Dim theName As String = Console.ReadLine()

        gradeBook.CourseName = theName 'set the courseName(invokes Set)
        Console.WriteLine() 'output a blank line

        'display welcome message including the course name(invokes Get)
        gradeBook.DisplayMessage()
        Console.ReadKey()
    End Sub

End Module

  类代码

'Fig. 4.7:GradeBook.vb                                               |-----------------------------------------------|
'GradeBook class that contains instance variable courseNameValue     |注:instance variable(实例变量)              |
'and a property to get and set its value.                            |property(属性包含set和get)                   |               
Public Class GradeBook                                              '|此类中包含一个方法Display和属性courseNameValue |
    Private courseNameValue As String 'course name for this GradeBook| Private声明实例变量                           |
    '                                                                |属性以访问限定符(public)开始                 |
    'property CourseName                                             |-----------------------------------------------|
    Public Property CourseName() As String
        Get 'retrieve courseNameValue(提取实例变量courseNameValue值)
            Return courseNameValue
        End Get
        Set(ByVal value As String) ' courseNameValue
            courseNameValue = value 'store the course name in the object
        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 & "!")
        '注:在方法中通过属性(CourseName)来操作对应的实例变量(courseNameValue)被认为是一种很好的做法
        '实际上就是调用了类的属性,从而返回了我们所需要的属性内经过运算的实例变量
    End Sub 'DiaplayMessage

End Class 'GradeBook

  

源于:visual basic 2008 how to program  P102

猜你喜欢

转载自www.cnblogs.com/xiehaofeng/p/10050741.html