共用方式為


How to: Access Members of an Object (Visual Basic)

When you have an object variable that refers to an object, you often want to work with the members of that object, such as its methods, properties, fields, and events. For example, once you have created a new Form object, you might want to set its Text property or call its Focus method.

Accessing Members

You access an object's members through the variable that refers to it.

To access members of an object

  • Use the member-access operator (.) between the object variable name and the member name.

    currentText = newForm.Text
    

    If the member is Shared (Visual Basic), you do not need a variable to access it.

Accessing Members of an Object of Known Type

If you know the type of an object at compile time, you can use early binding for a variable that refers to it.

To access members of an object for which you know the type at compile time

  1. Declare the object variable to be of the type of the object you intend to assign to the variable.

    Dim extraForm As System.Windows.Forms.Form
    

    With Option Strict On, you can assign only Form objects (or objects of a type derived from Form) to extraForm. If you have defined a class or structure with a widening CType conversion to Form, you can also assign that class or structure to extraForm.

  2. Use the member-access operator (.) between the object variable name and the member name.

    extraForm.Show()
    

    You can access all of the methods and properties specific to the Form class, no matter what the Option Strict setting is.

Accessing Members of an Object of Unknown Type

If you do not know the type of an object at compile time, you must use late binding for any variable that refers to it.

To access members of an object for which you do not know the type at compile time

  1. Declare the object variable to be of the Object Data Type. (Declaring a variable as Object is the same as declaring it as System.Object.)

    Dim someControl As Object
    

    With Option Strict On, you can access only the members that are defined on the Object class.

  2. Use the member-access operator (.) between the object variable name and the member name.

    someControl.GetType()
    

    To be able to access the members of any object you assign to the object variable, you must set Option Strict Off. When you do this, the compiler cannot guarantee that a given member is exposed by the object you assign to the variable. If the object does not expose a member you attempt to access, a MemberAccessException exception occurs.

See Also

Reference

Object Data Type

Option Strict Statement

Object

Form

MemberAccessException

Concepts

Object Variables in Visual Basic

Object Variable Declaration (Visual Basic)