我正在用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编辑:
好的,我学到了一些非常重要的东西,它改变了一切,我认为这对人们了解是有用的。多态和Implements关键字确实会对情况产生影响。
如果我有一个类foo和一个实现foo的类栏,那么
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发布于 2019-07-25 14:39:46
两者都是最好的?- TypeOf的类型安全性& Case的可读性/短路优势
Select Case True
Case TypeOf InputVariable Is Type1:
...
Case TypeOf InputVariable Is Type2:
...
Case TypeOf InputVariable Is Type3:
...
End Selecthttps://stackoverflow.com/questions/57204236
复制相似问题