【发布时间】:2014-07-18 08:41:46
【问题描述】:
请注意“包装”是否是正确的术语。本质上,我正在构建一个具有另一个类作为私有成员的类,并且我想在父接口中公开一些(不是全部)子类的功能。为简单起见,我以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
大概如果缺少可选参数,它会将Nothing 传递给m_ClsMyCollection.Add 中的那些参数,但我怀疑传递Nothing 并不等于根本不传递参数。
替代方法似乎是检查每个 arg 上的 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 个案例!这是必要的吗?有没有更好的办法?
【问题讨论】: