确定对象类型

更新:2007 年 11 月

一般对象变量(即声明为 Object 的变量)可以包含来自任何类的对象。当使用 Object 类型的变量时,可能需要基于对象的类采取不同的操作;例如,有些对象可能不支持特定的属性或方法。Visual Basic 提供了两种方式来确定对象变量中存储的对象类型:TypeName 函数和 TypeOf...Is 运算符。

TypeName 和 TypeOf…Is

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

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

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

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

这里应该提醒您几句。如果对象属于某一特定类型或是从特定类型派生的,则 TypeOf...Is 运算符会返回 True。您用 Visual Basic 所做的几乎每项操作都涉及对象(包括通常不被视为对象的某些元素,例如字符串和整数)。这些对象均从 Object 派生并从其中继承方法。当向 TypeOf...Is 运算符传递一个 Integer 并用 Object 计算它时,它返回 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...Is 和 TypeName 来确定在 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
    

请参见

概念

使用字符串名调用属性或方法

参考

Object 数据类型

TypeName 函数 (Visual Basic)

If...Then...Else 语句 (Visual Basic)

String 数据类型 (Visual Basic)

Integer 数据类型 (Visual Basic)

其他资源

在运行时获取类信息