带可选参数的VBA包装方法
请注意,确保“包装”是正确的术语。本质上,我正在构建一个类,该类将另一个类作为私有成员,并且我希望在父类的接口中公开子类的一些(不是全部)函数。为了简化示例,我将使用带可选参数的VBA包装方法,vba,wrapper,Vba,Wrapper,请注意,确保“包装”是正确的术语。本质上,我正在构建一个类,该类将另一个类作为私有成员,并且我希望在父类的接口中公开子类的一些(不是全部)函数。为了简化示例,我将使用集合作为示例: 'MyClass Private m_ClsMyCollection As Collection ... 'Expose Collection.Count Public Function Count() As Long Count = m_ClsMyCollection.Count End Sub 这很
集合
作为示例:
'MyClass
Private m_ClsMyCollection As Collection
...
'Expose Collection.Count
Public Function Count() As Long
Count = m_ClsMyCollection.Count
End Sub
这很简单,但在使用可选参数公开方法时,我遇到了一个问题。例如,Collection.Add
声明为
Collection.Add(Item, [Key], [Before], [After])
我不知道怎么包装这个。简单地执行以下操作是否安全:
Public Sub Add(Item, Optional Key, Optional Before, Optional After)
m_ClsMyCollection.Add Item, Key, Before, After
End Sub
假设如果缺少可选参数,它将向m_ClsMyCollection.Add
中的那些参数传递Nothing
,但我怀疑传递Nothing
并不等于根本不传递参数
另一种方法似乎是在每个参数上检查IsMissing
,并为每个可能的参数组合编写一个pass,这似乎很疯狂:
Public Sub Add(Item, Optional Key, Optional Before, Optional After)
If IsMissing(Key) And IsMissing(Before) And IsMissing(After) Then
m_ClsMyCollection.Add Item:=Item
ElseIf IsMissing(Key) And IsMissing(Before) Then
m_ClsMyCollection.Add Item:=Item, After:=After
ElseIf IsMissing(Key) And IsMissing(After) Then
m_ClsMyCollection.Add Item:=Item, Before:=Before
...
End Sub
组合的数量随着可选参数的数量呈指数增长-即使只有3个,我也需要检查8个案例!这有必要吗?有更好的方法吗?我可以通过执行以下操作来测试这一点:
Public Sub Foo()
Wrapper
End Sub
Public Sub Wrapper(Optional MyArg)
Wrapped MyArg
End Sub
Public Sub Wrapped(Optional MyArg)
Debug.Print IsMissing(MyArg)
End Sub
这将输出
True
,证明无需检查是否传递了每个可选参数-在上述情况下,m_ClsMyCollection.Add Item,Key,Before,无论传递了哪些参数,
之后就足够了。为了完整性:在中发生的是当Wrapper
调用Wrapped MyArg
时,MyArg
的值为Missing
。因此,即使它实际上被传递到Wrapped
,它的值为Missing
,因此,IsMissing
的计算结果为true。(这样做完全安全。)