请注意“包装”是否是正确的术语。本质上,我正在构建一个类,该类具有另一个类作为私有(private)成员,并且我想在父类的接口(interface)中公开子类的一些(不是全部)函数。为了使示例简单,我将使用 Collection
作为示例:
'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
,并为每种可能的参数组合编写一个传递,这看起来很疯狂:
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 , After
就足够了,无论传递哪些参数。