如何限制 VB.NET 中的 ParamArray 边界?

How to limit ParamArray Bounds In VB.NET?

我正在研究接受 ParamArrays 的函数。但它应该至少有一个元素,最多有 5 个元素。我尝试定义数组边界但出现错误 Array bounds cannot appear in type specifiers.

那我该怎么做呢?

So how can I do this?

你不能。至少不是静态的。您唯一可以做的就是检查函数内部并在遇到错误数量的参数时抛出异常(例如 ArgumentException)。

然而,就 API 设计而言,这让我觉得很奇怪。我不认为 ParamArray 是您情况下的最佳解决方案,正是因为您似乎有 ParamArray.

没有很好反映的限制

不知道你问题的上下文,我建议尽你所能使函数签名符合你需要的合同。例如:

Public Sub Grover (cheese1 as Cheese, Optional cheese2 as Cheese = Nothing, Optional cheese3 as Cheese = Nothing, Optional cheese4 as Cheese = Nothing, Optional cheese5 as Cheese = Nothing)
    If cheese1 Is Nothing Then
        'throw
    End If

    For Each cheese in {cheese1, cheese2, cheese3, cheese4, cheese5}
        If cheese IsNot Nothing Then
            cheese.Snozzle()
        End If

        'or, in VB14 (as of Visual Studio 2015)
        cheese?.Snozzle()
    Next
End Sub