Compartilhar via


Como: Determinar a qual tipo uma variável de objeto se refere (Visual Basic)

An object variable contains a pointer to data that is stored elsewhere. The type of that data can change during run time. At any moment, you can use the GetTypeCode method to determine the current run-time type, or the Operador TypeOf (Visual Basic) to find out if the current run-time type is compatible with a specified type.

To determine the exact type an object variable currently refers to

  1. On the object variable, call the GetType method to retrieve a System.Type object.

    Dim myObject As Object
    myObject.GetType()
    
  2. On the System.Type class, call the shared method GetTypeCode to retrieve the TypeCode enumeration value for the object's type.

    Dim myObject As Object
    Dim datTyp As Integer = Type.GetTypeCode(myObject.GetType())
    MsgBox("myObject currently has type code " & CStr(datTyp))
    

    You can test the TypeCode enumeration value against whichever enumeration members are of interest, such as Double.

To determine whether an object variable's type is compatible with a specified type

  • Use the TypeOf operator in combination with the Operador Is (Visual Basic) to test the object with a TypeOf...Is expression.

    If TypeOf objA Is System.Windows.Forms.Control Then
        MsgBox("objA is compatible with the Control class")
    End If
    

    The TypeOf...Is expression returns True if the object's run-time type is compatible with the specified type.

    The criterion for compatibility depends on whether the specified type is a class, structure, or interface. In general, the types are compatible if the object is of the same type as, inherits from, or implements the specified type. For more information, see Operador TypeOf (Visual Basic).

Compilando o código

Note that the specified type cannot be a variable or expression. It must be the name of a defined type, such as a class, structure, or interface. This includes intrinsic types such as Integer and String.

Consulte também

Referência

Tipo de dados Object

GetType

System.Type

GetTypeCode

TypeCode

Conceitos

Variáveis de objeto no Visual Basic

Valores de variável de objeto (Visual Basic)