【问题标题】:VB6 Runtime Type RetrievalVB6 运行时类型检索
【发布时间】:2010-09-08 07:20:24
【问题描述】:

VB6运行时如何获取Object的Type(字符串形式即可)?

即类似:

If Typeof(foobar) = "CommandButton" Then ...

/EDIT: 澄清一下,我需要检查动态类型对象。一个例子:

Dim y As Object 

Set y = CreateObject("SomeType")

Debug.Print( <The type name of> y)

输出将是“CommandButton”

【问题讨论】:

    标签: vb6 runtime


    【解决方案1】:

    TypeName 是你想要的...这是一些示例输出:

    VB6 代码:

    Private Sub cmdCommand1_Click()
    Dim a As Variant
    Dim b As Variant
    Dim c As Object
    Dim d As Object
    Dim e As Boolean
    
    a = ""
    b = 3
    Set c = Me.cmdCommand1
    Set d = CreateObject("Project1.Class1")
    e = False
    
    Debug.Print TypeName(a)
    Debug.Print TypeName(b)
    Debug.Print TypeName(c)
    Debug.Print TypeName(d)
    Debug.Print TypeName(e)
    End Sub
    

    结果:

    String
    Integer
    CommandButton
    Class1
    Boolean
    

    【讨论】:

      【解决方案2】:

      我认为您正在寻找的是 TypeName 而不是 TypeOf。

      If TypeName(foobar) = "CommandButton" Then
         DoSomething
      End If
      

      编辑:动态对象是什么意思?你的意思是创建的对象 CreateObject(""),因为它仍然可以工作。

      编辑:

      Private Sub Command1_Click()
          Dim oObject As Object
          Set oObject = CreateObject("Scripting.FileSystemObject")
          Debug.Print "Object Type: " & TypeName(oObject)
      End Sub
      

      输出

      Object Type: FileSystemObject

      【讨论】:

      • 也许我应该澄清我的问题,我想知道动态类型的对象是什么,所以使用 TypeName 将(在我的情况下)只返回“对象”。
      【解决方案3】:

      我手头没有VB6,但我认为你需要

      Typename()
      

      function...我可以在 Excel VBA 中看到它,所以它可能在同一个运行时。有趣的是,帮助似乎表明它不应该适用于用户定义的类型,但这是我曾经确实使用它的唯一方式。

      帮助文件摘录:

      类型名称函数

      返回一个提供变量信息的字符串。

      语法

      类型名(变量名)

      所需的 varname 参数是 包含任何变量的变体,除了 用户定义类型的变量。

      【讨论】:

        【解决方案4】:

        这应该很困难,因为在 VB6 中所有对象都是 COM (IDispatch) 的东西。因此它们只是一个接口。

        TypeOf(object) is class 可能只进行 COM get_interface 调用(我忘记了确切的方法名称,抱歉)。

        【讨论】:

          猜你喜欢
          • 2013-11-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-07-15
          • 2012-10-05
          • 1970-01-01
          相关资源
          最近更新 更多