Visual Basic 中的物件和類別Objects and classes in Visual Basic

「物件」是可視為一個單位的程式碼和資料組合。An object is a combination of code and data that can be treated as a unit. 物件可以是應用程式的一部分，例如控制項或表單。An object can be a piece of an application, like a control or a form. 整個應用程式也可以是一個物件。An entire application can also be an object.

物件和類別Objects and classes

Visual Basic 中的每個物件都是由類別所定義。Each object in Visual Basic is defined by a class. 類別會描述物件的變數、屬性、程序及事件。A class describes the variables, properties, procedures, and events of an object. 物件是類別的執行個體；當您定義類別之後，就能視需要建立最多的物件。Objects are instances of classes; you can create as many objects you need once you have defined a class.

從類別建立物件To create an object from a class

1. 決定您要從哪一個類別建立物件。Determine from which class you want to create an object.

2. 撰寫 Dim 陳述式來建立變數，而您可以將類別執行個體指派給該變數。Write a Dim Statement to create a variable to which you can assign a class instance. 變數必須是所需類別的型別。The variable should be of the type of the desired class.

Dim nextCustomer As customer

3. 新增 New 運算子關鍵字，將變數初始化為類別的新執行個體。Add the New Operator keyword to initialize the variable to a new instance of the class.

Dim nextCustomer As New customer

4. 您現在可以透過物件變數存取類別的成員。You can now access the members of the class through the object variable.

nextCustomer.accountNumber = lastAccountNumber + 1


物件成員Object members

成員存取Member Access

warningLabel.Text = "Data not saved"


欄位和屬性Fields and properties

「欄位」和「屬性」表示物件中所儲存的資訊。Fields and properties represent information stored in an object. 您可以利用在程序中擷取和設定區域變數的相同方式，使用指派陳述式來擷取和設定它們的值。You retrieve and set their values with assignment statements the same way you retrieve and set local variables in a procedure. 下列範例會擷取 Label 物件的 Width 屬性，並設定 ForeColor 屬性。The following example retrieves the Width property and sets the ForeColor property of a Label object.

Dim warningWidth As Integer = warningLabel.Width
warningLabel.ForeColor = System.Drawing.Color.Red


• 您需要控制何時以及如何設定或擷取值。You need to control when and how a value is set or retrieved.

• 屬性具有一組定義明確且需要驗證的值。The property has a well-defined set of values that need to be validated.

• 設定值會導致一些可察覺的物件狀態變更，例如 IsVisible 屬性。Setting the value causes some perceptible change in the object's state, such as an IsVisible property.

• 設定此屬性會導致其他內部變數的變更，或其他屬性值的變更。Setting the property causes changes to other internal variables or to the values of other properties.

• 您必須先執行一組步驟，才能設定或擷取此屬性。A set of steps must be performed before the property can be set or retrieved.

• 值為自我驗證的型別。The value is of a self-validating type. 例如，如果將 TrueFalse 以外的值指派給 Boolean 變數，就會發生錯誤或自動資料轉換。For example, an error or automatic data conversion occurs if a value other than True or False is assigned to a Boolean variable.

• 位於資料型別所支援範圍內的任何值都是有效的。Any value in the range supported by the data type is valid. 這適用許多型別為 SingleDouble 的屬性。This is true of many properties of type Single or Double.

• 屬性是 String 資料型別，而且對於字串的大小或值沒有任何限制。The property is a String data type, and there is no constraint on the size or value of the string.

方法Methods

「方法」是物件可執行的動作。A method is an action that an object can perform. 例如，AddComboBox 物件的方法，可新增項目至下拉式方塊。For example, Add is a method of the ComboBox object that adds a new entry to a combo box.

Dim safetyTimer As New System.Windows.Forms.Timer
safetyTimer.Start()


執行個體成員和共用的成員Instance members and shared members

存取非共用的成員Accessing nonshared members

存取物件的非共用成員To access a nonshared member of an object
1. 確定物件是從它的類別所建立，並將它指派給物件變數。Make sure the object has been created from its class and assigned to an object variable.

Dim secondForm As New System.Windows.Forms.Form

2. 在存取成員的陳述式中，在物件變數名稱後面加上「成員存取運算子」(.)，然後是成員名稱。In the statement that accesses the member, follow the object variable name with the member-access operator (.) and then the member name.

secondForm.Show()


存取共用的成員Accessing shared members

存取物件的共用成員To access a shared member of an object
• 在類別名稱後面加上「成員存取運算子」 (.)，然後是成員名稱。Follow the class name with the member-access operator (.) and then the member name. 您應一律透過類別名稱直接存取物件的 Shared 成員。You should always access a Shared member of the object directly through the class name.

MsgBox("This computer is called " & Environment.MachineName)

• 如果您已經從類別建立物件，也可以透過物件的變數存取 Shared 成員。If you have already created an object from the class, you can alternatively access a Shared member through the object's variable.

類別和模組之間的差異Differences between classes and modules

Shared 修飾詞套用到類別成員時，它會與類別本身而不是類別的特定執行個體相關聯。When the Shared modifier is applied to a class member, it is associated with the class itself instead of a particular instance of the class. 使用類別名稱直接存取成員，相同方式可用來存取模組成員。The member is accessed directly by using the class name, the same way module members are accessed.

重複使用類別和物件Reusing classes and objects

.NET Framework 提供許多可供使用的元件範例。The .NET Framework provides many examples of components that are available for use. 下列範例使用 System 命名空間中的 TimeZone 類別。The following example uses the TimeZone class in the System namespace. TimeZone 提供可讓您擷取目前電腦系統時區相關資訊的成員。TimeZone provides members that allow you to retrieve information about the time zone of the current computer system.

Public Sub examineTimeZone()
Dim tz As System.TimeZone = System.TimeZone.CurrentTimeZone
Dim s As String = "Current time zone is "
s &= CStr(tz.GetUtcOffset(Now).Hours) & " hours and "
s &= CStr(tz.GetUtcOffset(Now).Minutes) & " minutes "
s &= "different from UTC (coordinated universal time)"
s &= vbCrLf & "and is currently "
If tz.IsDaylightSavingTime(Now) = False Then s &= "not "
s &= "on ""summer time""."
MsgBox(s)
End Sub


物件之間的關聯性Relationships among objects

階層式關聯性Hierarchical relationship

定義衍生自已經存在之類別的類別To define a class is derived from an already existing class

1. 使用 Class 陳述式來定義您需要從中建立物件的類別。Use a Class Statement to define a class from which to create the object you need.

Public Class reversibleButton


請確定 End Class 陳述式會接在類別中程式碼最後一行的後面。Be sure an End Class statement follows the last line of code in your class. 根據預設，當您輸入 Class 陳述式時，整合式開發環境 (IDE) 會自動產生 End ClassBy default, the integrated development environment (IDE) automatically generates an End Class when you enter a Class statement.

2. Class 陳述式正後方加上 Inherits 陳述式Follow the Class statement immediately with an Inherits Statement. 指定要從中衍生新類別的類別。Specify the class from which your new class derives.

Inherits System.Windows.Forms.Button


您的新類別會繼承由基底類別定義的所有成員。Your new class inherits all the members defined by the base class.

3. 加入衍生類別所公開之其他成員適用的程式碼。Add the code for the additional members your derived class exposes. 例如，您可以加入 reverseColors 方法，而您的衍生類別可能看起來如下：For example, you might add a reverseColors method, and your derived class might look as follows:

Public Class reversibleButton
Inherits System.Windows.Forms.Button
Public Sub reverseColors()
Dim saveColor As System.Drawing.Color = Me.BackColor
Me.BackColor = Me.ForeColor
Me.ForeColor = saveColor
End Sub
End Class


如果您從 reversibleButton 類別建立物件，則它可存取 Button 類別的所有成員，以及 reverseColors 方法和您在 reversibleButton 上定義的任何其他新成員。If you create an object from the reversibleButton class, it can access all the members of the Button class, as well as the reverseColors method and any other new members you define on reversibleButton.