确定对象类型 (Visual Basic)

泛型对象变量(即声明为 Object变量)可以保存任何类中的对象。 使用类型的 Object变量时,可能需要根据对象的类执行不同的作;例如,某些对象可能不支持特定的属性或方法。 Visual Basic 提供了两种确定对象类型存储在对象变量中的方法: TypeName 函数和 TypeOf...Is 运算符。

TypeName 和 TypeOf…Is

TypeName 函数返回一个字符串,当你需要存储或显示对象的类名时,这是最佳选择,如以下代码片段所示:

Dim Ctrl As Control = New TextBox
MsgBox(TypeName(Ctrl))

运算符 TypeOf...Is 是测试对象类型的最佳选择,因为它比使用 TypeName等效字符串比较快得多。 以下代码片段在 TypeOf...Is 语句中使用 If...Then...Else

If TypeOf Ctrl Is Button Then
    MsgBox("The control is a button.")
End If

此处需要提醒一下。 如果对象是特定类型,或者派生自特定类型,则 TypeOf...Is 运算符返回 True 。 使用 Visual Basic 执行的所有作几乎都涉及对象,其中包括一些通常不被视为对象(如字符串和整数)的元素。 这些对象从Object派生并继承方法。 当传递 Integer 并用 Object 进行计算时,TypeOf...Is 运算符返回 True。 以下示例报告参数 InParam 既是参数 Object ,又是一个 Integer

Sub CheckType(ByVal InParam As Object)
    ' Both If statements evaluate to True when an
    ' Integer is passed to this procedure.
    If TypeOf InParam Is Object Then
        MsgBox("InParam is an Object")
    End If
    If TypeOf InParam Is Integer Then
        MsgBox("InParam is an Integer")
    End If
End Sub

以下示例使用TypeOf...IsTypeName来确定通过Ctrl参数传递给它的对象类型。 过程 TestObject 使用三种不同类型的控件调用 ShowType

运行示例

  1. 创建新的 Windows 应用程序项目,并向窗体添加 Button 控件、 CheckBox 控件和 RadioButton 控件。

  2. 通过窗体上的按钮调用 TestObject 过程。

  3. 将以下代码添加到表单:

    Sub ShowType(ByVal Ctrl As Object)
        'Use the TypeName function to display the class name as text.
        MsgBox(TypeName(Ctrl))
        'Use the TypeOf function to determine the object's type.
        If TypeOf Ctrl Is Button Then
            MsgBox("The control is a button.")
        ElseIf TypeOf Ctrl Is CheckBox Then
            MsgBox("The control is a check box.")
        Else
            MsgBox("The object is some other type of control.")
        End If
    End Sub
    
    Protected Sub TestObject()
        'Test the ShowType procedure with three kinds of objects.
        ShowType(Me.Button1)
        ShowType(Me.CheckBox1)
        ShowType(Me.RadioButton1)
    End Sub
    

另请参阅