将常量数组传递给 VB.NET 中的函数
我知道您可以轻松地将数组传递给函数,如下面的代码所示,
Private Sub SomeFunction(ByVal PassedArray() As String)
For i As Integer = 0 To PassedArray.Count - 1
Debug.WriteLine(PassedArray(i))
Next
End Sub
Public Sub Test()
Dim MyArray As String() = {"some", "array", "members"}
SomeFunction(MyArray)
End Sub
但是有没有办法将常量数组传递给 VB.NET 中的函数?
例如,在 PHP 中,您可以这样写:
function SomeFunction($array)
{
for($i=0;$i<count($array);$i++)
{
echo($array[$i]);
}
}
function Test()
{
SomeFunction(array("some", "array", "members")); // Works for PHP
}
那么重申一下:有没有办法将常量数组直接传递给 VB.NET 中的函数? 这样做有什么好处吗? 我想可以节省几个字节的内存。
附:
SomeFunction({"some", "array", "member"}) ' This obviously gives a syntax error
I know that you can easily pass an array to a function, like the code below shows
Private Sub SomeFunction(ByVal PassedArray() As String)
For i As Integer = 0 To PassedArray.Count - 1
Debug.WriteLine(PassedArray(i))
Next
End Sub
Public Sub Test()
Dim MyArray As String() = {"some", "array", "members"}
SomeFunction(MyArray)
End Sub
But is there a way to pass a constant array to a function in VB.NET?
For instance in PHP, you could write:
function SomeFunction($array)
{
for($i=0;$i<count($array);$i++)
{
echo($array[$i]);
}
}
function Test()
{
SomeFunction(array("some", "array", "members")); // Works for PHP
}
So to reiterate: Is there a way to pass a constant array directly to a function in VB.NET? Is there any benefit in doing so? I imagine a few bytes of memory could be spared.
PS.:
SomeFunction({"some", "array", "member"}) ' This obviously gives a syntax error
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不; CLI 中没有常量数组这样的东西; 数组总是可变的。 也许
ReadOnlyCollection
会适用?在 C# 中(大概与 VB 中类似),您可以执行以下操作:
这为您提供了一个静态(=共享)不可编辑、可重用的集合。 如果该方法接受
IList
、IEnumerable
等(而不是数组T[]
),则此方法尤其有效。No; there is no such thing as a constant array in CLI; arrays are always mutable. Perhaps a
ReadOnlyCollection<T>
would be suitable?In C# (so presumably similar in VB) you can do something like:
Which gives you a static (=shared) non-editable, re-usable collection. This works especially well if the method accepts
IList<T>
,IEnumerable<T>
, etc (rather than an array,T[]
).这是从 VB10 (Visual Studio 2010) 开始的完全有效的语法。 请参阅:
This is a perfectly valid syntax starting with VB10 (Visual Studio 2010). See this:
我刚刚想到的另一件事并没有直接回答问题,但也许可以理解发布者的意图 - ParamArray 关键字。 如果您控制所调用的函数,这可以使生活变得更加轻松。
Another thing I just thought of that doesn't directly answer the question, but perhaps gets at the poster's intent - the ParamArray keyword. If you control the function you are calling into, this can make life a whole lot easier.
您可以做的最接近的是:
这实际上与您发布的创建的对象相同。 .NET 中实际上并没有数组文字,只是用于初始化的帮助程序。
The closest you can do is:
This is actually identical in terms of objects created to what you posted. There aren't actually array literals in .NET, just helpers for initialization.