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.

當您在 Visual Basic 中建立應用程式時,您會經常使用物件。When you create an application in Visual Basic, you constantly work with objects. 您可以使用 Visual Basic 所提供的物件,例如控制項、表單和資料存取物件。You can use objects provided by Visual Basic, such as controls, forms, and data access objects. 您也可以使用來自 Visual Basic 應用程式中其他應用程式的物件。You can also use objects from other applications within your Visual Basic application. 您甚至可以建立自己的物件,並為其定義其他屬性和方法。You can even create your own objects and define additional properties and methods for them. 物件的作用類似針對程式預製的建置組塊 - 它們可讓您撰寫一段程式碼一次,然後不斷地重複使用。Objects act like prefabricated building blocks for programs — they let you write a piece of code once and reuse it over and over.

本主題會詳細討論物件。This topic discusses objects in detail.

物件和類別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 understand the relationship between an object and its class, think of cookie cutters and cookies. 餅乾壓模是類別。The cookie cutter is the class. 它會定義每塊餅乾的特性,例如大小和形狀。It defines the characteristics of each cookie, for example size and shape. 類別可用來建立物件。The class is used to create objects. 物件則是餅乾。The objects are the cookies.

您必須先建立物件,然後才能存取它的成員。You must create an object before you can access its members.

從類別建立物件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
    

注意

可能的話,您應該將變數宣告為您想要指派給它的類別型別。Whenever possible, you should declare the variable to be of the class type you intend to assign to it. 這稱為「早期繫結」。This is called early binding. 如果您在編譯時期不知道類別類型,可藉由將變數宣告為 Object 資料類型來叫用「晚期繫結」。If you don't know the class type at compile time, you can invoke late binding by declaring the variable to be of the Object Data Type. 不過,晚期繫結會讓效能降低,並限制存取執行階段物件的成員。However, late binding can make performance slower and limit access to the run-time object's members. 如需詳細資訊,請參閱物件變數宣告For more information, see Object Variable Declaration.

多重執行個體Multiple instances

從類別新建的物件通常是彼此相同的。Objects newly created from a class are often identical to each other. 不過,當它們以個別物件存在之後,就能個別變更其變數和屬性,而與其他執行個體無關。Once they exist as individual objects, however, their variables and properties can be changed independently of the other instances. 例如,如果您在表單中新增三個核取方塊,每個核取方塊物件都是 CheckBox 類別的執行個體。For example, if you add three check boxes to a form, each check box object is an instance of the CheckBox class. 個別的 CheckBox 物件會共用一組由類別所定義的通用特性和功能 (屬性、變數、程序及事件)。The individual CheckBox objects share a common set of characteristics and capabilities (properties, variables, procedures, and events) defined by the class. 但是,每個物件都有自己的名稱、可個別啟用及停用,而且可以放在表單的不同位置。However, each has its own name, can be separately enabled and disabled, and can be placed in a different location on the form.

物件成員Object members

物件是應用程式的元素,代表類別的「執行個體」。An object is an element of an application, representing an instance of a class. 欄位、屬性、方法及事件都是物件的建置組塊,並構成它們的「成員」。Fields, properties, methods, and events are the building blocks of objects and constitute their members.

成員存取Member Access

您可以存取物件的成員,方法是依序指定物件變數的名稱、句點 (.) 及成員的名稱。You access a member of an object by specifying, in order, the name of the object variable, a period (.), and the name of the member. 下列範例會設定 Label 物件的 Text 屬性。The following example sets the Text property of a Label object.

warningLabel.Text = "Data not saved"

成員的 IntelliSense 清單IntelliSense listing of members

當您叫用 IntelliSense 的 [列出成員] 選項時 (例如,當您輸入句號 (.) 做為成員存取運算子時),它會列出類別的成員。IntelliSense lists members of a class when you invoke its List Members option, for example when you type a period (.) as a member-access operator. 如果您在宣告為該類別執行個體的變數名稱後面輸入句點,IntelliSense 會列出所有執行個體成員,而不會列出任何共用的成員。If you type the period following the name of a variable declared as an instance of that class, IntelliSense lists all the instance members and none of the shared members. 如果您在類別名稱本身後面輸入句點,則 IntelliSense 會列出所有共用的成員,但不會列出任何執行個體成員。If you type the period following the class name itself, IntelliSense lists all the shared members and none of the instance members. 如需詳細資訊,請參閱使用 IntelliSenseFor more information, see Using IntelliSense.

欄位和屬性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

請注意,也會呼叫欄位做為「成員變數」。Note that a field is also called a member variable.

使用屬性程序的時機:Use property procedures when:

  • 您需要控制何時以及如何設定或擷取值。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.

使用欄位的時機:Use fields when:

  • 值為自我驗證的型別。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.

  • 如需詳細資訊,請參閱屬性程序For more information, see Property Procedures.

方法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.

下列範例示範 Timer 物件的 Start 方法。The following example demonstrates the Start method of a Timer object.

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

請注意,方法只是物件所公開的「程序」。Note that a method is simply a procedure that is exposed by an object.

如需詳細資訊,請參閱程序For more information, see Procedures.

EventsEvents

事件是物件所識別的動作 (例如按一下滑鼠按鈕或按下按鍵),而您可以撰寫程式碼來回應。An event is an action recognized by an object, such as clicking the mouse or pressing a key, and for which you can write code to respond. 事件可能因使用者動作或程式碼而發生,或由系統所導致。Events can occur as a result of a user action or program code, or they can be caused by the system. 您可以將對事件發出訊號的程式碼視為「引發」事件,而將回應事件的程式碼視為「處理」它。Code that signals an event is said to raise the event, and code that responds to it is said to handle it.

您也可以開發自己的自訂事件,透過您的物件來引發並由其他物件來處理。You can also develop your own custom events to be raised by your objects and handled by other objects. 如需詳細資訊,請參閱事件For more information, see Events.

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

當您從類別建立物件時,會產生該類別的執行個體。When you create an object from a class, the result is an instance of that class. 未使用 Shared 關鍵字宣告的成員是「執行個體成員」,它們完全屬於該特定執行個體。Members that are not declared with the Shared keyword are instance members, which belong strictly to that particular instance. 一個執行個體中的執行個體成員,與同一個類別的另一個執行個體中相同的成員無關。An instance member in one instance is independent of the same member in another instance of the same class. 例如,執行個體成員變數可以在不同執行個體中具有不同的值。An instance member variable, for example, can have different values in different instances.

使用 Shared 關鍵字宣告的成員是「共用的成員」,它們屬於整個類別,而不屬於任何特定執行個體。Members declared with the Shared keyword are shared members, which belong to the class as a whole and not to any particular instance. 共用的成員只會存在一次,而不論您為它的類別建立了多少個執行個體,或者,即使您未建立任何執行個體也一樣。A shared member exists only once, no matter how many instances of its class you create, or even if you create no instances. 例如,共用的成員變數只有一個值,可供可存取該類別的所有程式碼使用。A shared member variable, for example, has only one value, which is available to all code that can access the class.

存取非共用的成員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

類別和模組的主要差異是,類別可以具現化為物件,而標準模組不行。The main difference between classes and modules is that classes can be instantiated as objects while standard modules cannot. 因為只有一個標準模組資料的複本,所以,當您程式的某一部分變更了標準模組中的公用變數時,如果該程式的任何其他部分接著讀取該變數,則會取得相同的值 。Because there is only one copy of a standard module's data, when one part of your program changes a public variable in a standard module, any other part of the program gets the same value if it then reads that variable. 相較之下,每個具現化物件適用的物件資料會個別存在。In contrast, object data exists separately for each instantiated object. 另一個差異是,不同於標準模組,類別可以實作介面。Another difference is that unlike standard modules, classes can implement interfaces.

注意

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.

類別和模組也會針對它們的成員使用不同的範圍。Classes and modules also use different scopes for their members. 在類別內定義的成員範圍會在類別的特定執行個體內,而且只存在於物件的存留期。Members defined within a class are scoped within a specific instance of the class and exist only for the lifetime of the object. 若要從類別外部存取類別成員,您必須使用 Object.Member 格式的完整名稱。To access class members from outside a class, you must use fully qualified names in the format of Object.Member.

另一方面,在模組內宣告的成員預設是可公開存取的,而且可由任何可存取該模組的程式碼存取。On the other hand, members declared within a module are publicly accessible by default, and can be accessed by any code that can access the module. 這表示,標準模組中的變數是有效的全域變數 (因為您可以在專案中的任何位置看見它們),並存在於程式的存留期。This means that variables in a standard module are effectively global variables because they are visible from anywhere in your project, and they exist for the life of the program.

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

物件可讓您宣告變數和程序一次,接著就能在需要時重複使用它們。Objects let you declare variables and procedures once and then reuse them whenever needed. 例如,如果您想要在應用程式中加入拼字檢查程式,您可以定義所有變數和支援函式來提供拼字檢查功能。For example, if you want to add a spelling checker to an application you could define all the variables and support functions to provide spell-checking functionality. 如果您以類別形式建立拼字檢查程式,接著就能藉由加入對已編譯組件的參考,在其他應用程式中重複使用它。If you create your spelling checker as a class, you can then reuse it in other applications by adding a reference to the compiled assembly. 更棒的是,您或許能夠使用其他人已經開發的拼字檢查程式類別來簡化您的一些工作。Better yet, you may be able to save yourself some work by using a spelling checker class that someone else has already developed.

.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

在上述範例中,第一個 Dim 陳述式會宣告 TimeZone 類型的物件變數,並將 CurrentTimeZone 屬性所傳回的 TimeZone 物件指派給它。In the preceding example, the first Dim Statement declares an object variable of type TimeZone and assigns to it a TimeZone object returned by the CurrentTimeZone property.

物件之間的關聯性Relationships among objects

物件可以透過數種方式彼此相關。Objects can be related to each other in several ways. 主要的關聯性種類是「階層式」和「內含項目」。The principal kinds of relationship are hierarchical and containment.

階層式關聯性Hierarchical relationship

當類別衍生自更基本的類別時,即表示它們具有「階層式關聯性」。When classes are derived from more fundamental classes, they are said to have a hierarchical relationship. 在描述屬於更一般類別的子型別的項目時,類別階層架構就很實用。Class hierarchies are useful when describing items that are a subtype of a more general class.

在下列範例中,假設您想要定義一種特殊的 Button,其作用就像一般的 Button,但也會公開可反轉前景和背景色彩的方法。In the following example, suppose you want to define a special kind of Button that acts like a normal Button but also exposes a method that reverses the foreground and background colors.

定義衍生自已經存在之類別的類別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.

衍生的類別會繼承來自其基礎類別的成員,可讓您在類別階層中進行時增加複雜度。Derived classes inherit members from the class they are based on, allowing you to add complexity as you progress in a class hierarchy. 如需詳細資訊,請參閱繼承的基本概念For more information, see Inheritance Basics.

編譯程式碼Compiling the code

確定編譯器可以存取您想要從中衍生新類別的類別。Be sure the compiler can access the class from which you intend to derive your new class. 這可能表示要提供它的完整名稱,如同在上述範例中,或在 Imports 陳述式 (.NET 命名空間和型別)中識別它的命名空間。This might mean fully qualifying its name, as in the preceding example, or identifying its namespace in an Imports Statement (.NET Namespace and Type). 如果類別位於不同專案,則您可能需要加入對該專案的參考。If the class is in a different project, you might need to add a reference to that project. 如需詳細資訊,請參閱管理專案中的參考For more information, see Managing references in a project.

內含項目關聯性Containment relationship

另一個可讓物件相關聯的方法是「內含項目關係」。Another way that objects can be related is a containment relationship. 容器物件邏輯上會封裝其他物件。Container objects logically encapsulate other objects. 例如,OperatingSystem 物件在邏輯上會包含 Version 物件,這會透過其 Version 屬性傳回。For example, the OperatingSystem object logically contains a Version object, which it returns through its Version property. 請注意,容器物件實際上不會包含任何其他物件。Note that the container object does not physically contain any other object.

集合Collections

物件內含項目的一個特定型別是由「集合」來代表。One particular type of object containment is represented by collections. 集合是一組可列舉的相似物件。Collections are groups of similar objects that can be enumerated. Visual Basic 在 For Each 中支援特定的語法 ... 下一個語句,可讓您逐一查看集合的專案。Visual Basic supports a specific syntax in the For Each...Next Statement that allows you to iterate through the items of a collection. 此外,集合通常可讓您使用 Item[String],依其索引來擷取項目,或者將它們關聯至唯一字串來擷取項目。Additionally, collections often allow you to use an Item[String] to retrieve elements by their index or by associating them with a unique string. 比起陣列,集合更容易使用,因為它們讓您不需使用索引,就能新增或移除項目。Collections can be easier to use than arrays because they allow you to add or remove items without using indexes. 由於集合易於使用,因此,通常會用來儲存表單和控制項。Because of their ease of use, collections are often used to store forms and controls.

逐步解說:定義類別Walkthrough: Defining Classes
提供如何建立類別的逐步說明。Provides a step-by-step description of how to create a class.

多載屬性和方法Overloaded Properties and Methods
多載屬性和方法Overloaded Properties and Methods

繼承的基本概念Inheritance Basics
涵蓋繼承修飾詞,覆寫方法和屬性、MyClass 及 MyBase。Covers inheritance modifiers, overriding methods and properties, MyClass, and MyBase.

物件存留期:如何建立和終結物件Object Lifetime: How Objects Are Created and Destroyed
討論類別執行個體的建立與處置。Discusses creating and disposing of class instances.

匿名型別Anonymous Types
描述如何建立和使用匿名型別,讓您不需撰寫資料型別的類別定義,就能建立物件。Describes how to create and use anonymous types, which allow you to create objects without writing a class definition for the data type.

物件初始化運算式:\ 命名和匿名型別Object Initializers: Named and Anonymous Types</span> 討論物件初始設定式,它們可用於透過使用單一運算式來建立具名和匿名型別的執行個體。Discusses object initializers, which are used to create instances of named and anonymous types by using a single expression.

如何:在匿名型別宣告中推斷屬性名稱和類型How to: Infer Property Names and Types in Anonymous Type Declarations
說明如何在匿名型別宣告中推斷屬性名稱和型別。Explains how to infer property names and types in anonymous type declarations. 提供成功和失敗的推斷範例。Provides examples of successful and unsuccessful inference.