类型名称与变量类型 [英] TypeName vs VarType

查看:31
本文介绍了类型名称与变量类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查 Variant 的类型.可以使用 TypeNameVarType 来实现.我想使用 VarType 更有效,因为它不涉及字符串比较,只是数字比较.有什么理由更喜欢 TypeName?

I want to check the type of a Variant. It is possible to do it with TypeName and VarType. I guess that using VarType is more efficient, since it doesn't involve String comparison, just a numeric comparison. Any reason for preferring TypeName?

Public Sub testType()
    Dim b() As Double
    Dim a As Variant
    a = b

    Debug.Print TypeName(a) = "Double()" 'True
    Debug.Print VarType(a) = vbArray + vbDouble 'True
End Sub

推荐答案

我的建议

VarType 用于 VbVarType 枚举涵盖的内置类型.将 TypeName 用于其他类型.我将在下面详细解释此建议.

Use VarType for built-in types covered by the VbVarType enumeration. Use TypeName for other types. I'll explain this recommendation in detail below.

性能

性能差异很可能可以忽略不计,尤其是当您使用 VBA 编写数据库应用程序时.

The performance difference is most likely negligible, especially if you use VBA to write database applications.

变量类型

VarType 的一大优点是它不使用魔法字符串:如果你拼错了 vbDouble,你会得到一个编译时错误(假设你使用了 Option Explicit,您应该这样做).如果你拼错了"Double()",你的代码只会默默地做错事.

The big advantage of VarType is that it does not use magic strings: If you misspell vbDouble, you get a compile time error (assuming that you use Option Explicit, which you should). If you misspell "Double()", you code will just silently do the wrong thing.

类型名称

TypeName 的优点是它也适用于 VbVarType 枚举未涵盖的类型:

The advantage of TypeName is that it also works for types which are not covered by the VbVarType enumeration:

Dim b As New Collection
Dim a As Variant
Set a = b

Debug.Print VarType(a)      ' Prints just the generic vbObject constant
Debug.Print TypeName(a)     ' Prints "Collection"

问题

请注意,如果变量包含具有默认属性的对象,VarType 返回默认属性中包含的值的类型,而不是 vbObject.以下是使用 MS Access VBA 的 TempVar 类的示例:

Note that if the variable contains an object with a default property, VarType returns the type of the value contained in the default property instead of vbObject. Here is an example using MS Access VBA's TempVar class:

TempVars("x") = 123

Dim a As Variant
Set a = TempVars("x")

Debug.Print VarType(a)  ' Prints vbInteger, the type of a.Value's current content.
                        ' (Value is TempVar's default property)

Debug.Print TypeName(a) ' Prints "TempVar"

这篇关于类型名称与变量类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆