Using a ParamArray, but requiring at least one parameter

对着背影说爱祢 提交于 2019-12-03 15:31:38

Another option to consider would be

Module ParamArrayTest
    Sub ShowThings(ParamArray MyThings() As Integer)
        For Each thing As Integer In MyThings
            Debug.Print("{0}", thing)
        Next
    End Sub

    ' Don't try to call without parameters:
    <Obsolete("Must have at least one parameter", True)> Sub ShowThings()
        Throw New ArgumentException("Must specify at least one parameter")
    End Sub

    Sub Test()
        ShowThings(3, 4, 5)
        ShowThings()
    End Sub
End Module

The <Obsolete()> tag with a second parameter of True informs the compiler that attempting to use the marked method should result in a compilation error. Since the method in question would be used when, and only when, an attempt is made to invoke the method without any parameters, it would cause an error only at such times. Note that method will not be used if an attempt is made to pass the method a zero-element array of Integer; in that case, the normal ParamArray form would be used.

I think that the option that you mentioned is the best option. Using clearer names for your parameters will make it less confusing:

Public Sub Subscribe(mainChannel As ChannelType, ParamArray otherChannels() As ChannelType)

The other option is to enforce it at run-time, but as you said it wouldn't fail as fast:

Public Sub Subscribe(ParamArray channels() As ChannelType)
    If channels.Count = 0 then
        Throw new InvalidOperationException("At least one channel is needed")
    End If
End Sub
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!