我正在用 VBA 编写一个函数,该函数的参数可以是多种不同类型,我想知道检查类型的最佳方法是什么以及每种方法有哪些优点和缺点。我正在考虑两种方法。
第一种方法是使用带有 TypeName 的案例选择。第二种方法是使用 TypeOf 有一个大的 if else 语句。
我认为方法 1 看起来更干净,可读性更好,但可能会出现拼写错误。我认为方法2具有编译安全性。有没有一种方法是普遍首选的?
'method 1
Select Case TypeName(InputVariable)
Case "Type1", "Type2", "Type3", "Type4"
'do something
Case Else
'do something else
End Select
'method 2
If TypeOf InputVariable Is Type1 Or_
TypeOf InputVariable Is Type2 Or_
TypeOf InputVariable Is Type3 Or_
TypeOf InputVariable Is Type4 Then
'do something
Else
'do something else
End If
Run Code Online (Sandbox Code Playgroud)
编辑:
好吧,我学到了一些非常重要的东西,它改变了一切,我认为这对人们了解很有用。多态性和 Implements 关键字确实会影响这种情况。
如果我有一个 foo 类和一个实现 foo 的类 bar 那么
Dim MyFoo As Foo
Dim MyBar As Bar 'Bar implements Foo so its a type of Foo
If TypeName(MyBar) = "Foo" Then
'this code doesnt run
End If
If TypeOf MyBar Is Foo Then
'this code does run
End If
If TypeName(MyFoo) = "Bar" Then
'this code doesnt run
End If
If TypeOf MyFoo Is Bar Then
'this code doesnt run
End If
Run Code Online (Sandbox Code Playgroud)
两者都最好?- 的类型安全性TypeOf和可读性/短路优势Case:
Select Case True
Case TypeOf InputVariable Is Type1
...
Case TypeOf InputVariable Is Type2
...
Case TypeOf InputVariable Is Type3
...
End Select
Run Code Online (Sandbox Code Playgroud)