DotNet · 2022年5月2日

确定对象类型

Visual Basic 语言概念  

确定对象类型

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

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

   MsgBox(TypeName(Ctrl))

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

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

这里应该提醒您几句。如果对象为特定类型或是从特定类型导出的,则 TypeOfIs 运算符返回
True。您在 Visual Basic .NET 中所执行的任何操作几乎都涉及对象,包括通常不视为对象的某些元素,例如
StringsIntegers。这些对象是从 System.Object 导出的并从它那里继承方法。当被传递
Integer 并对 Object 计算时,TypeOfIs 运算符返回
True。下面的示例报告参数 InParam 既是 Object 也是
Integer

Sub CheckType(ByVal InParam)
' 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

下面的示例同时使用 TypeOfIsTypeName 来确定在 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
数据类型
| TypeOf
| TypeName
函数
| If…Then…Else
语句
| String
数据类型
| Integer
数据类型

最新电影,电视剧,尽在午夜剧场

电影电视剧午夜不寂寞