VB.NET 如何声明已知长度的新空数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18074925/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VB.NET How to declare new empty array of known length
提问by SNag
Is there a way in VB.NET to declare an array, and later initialize it to a known length in the code? In other words, I'm looking for the VB.NET equivalent of the following C#.NET code:
在 VB.NET 中有没有办法声明一个数组,然后在代码中将其初始化为已知长度?换句话说,我正在寻找与以下 C#.NET 代码等效的 VB.NET:
string[] dest;
// more code here
dest = new string[src.Length];
I tried this in VB, and it didn't work.
我在 VB 中试过这个,没有用。
Dim dest() as string
' more code here
dest = New String(src.Length)
What am I missing?
我错过了什么?
NOTE: I can confirm that
注意:我可以确认
Dim dest(src.Length) as string
works, but is not what I want, since I'm looking to separate the declaration and initialization of the array.
有效,但不是我想要的,因为我希望将数组的声明和初始化分开。
回答by Abbas Amiri
The syntax of VB.NET in such a case is a little different. The equivalent of
在这种情况下,VB.NET 的语法有点不同。相当于
string[] dest;
// more code here
dest = new string[src.Length];
is
是
Dim dest As String()
' more code here
dest = New String(src.Length - 1) {}
回答by Brian Hooper
The normal way to do this would be to declare the array like so:-
执行此操作的正常方法是像这样声明数组:-
Dim my_array() As String
and later in the code
然后在代码中
ReDim my_array (src.Length - 1)
回答by Matt Wilko
You can use Redim
as already noted but this is the equivalent VB code to your C#
您可以Redim
按照已经提到的方式使用,但这是与 C# 等效的 VB 代码
Dim dest As String()
dest = New String(src.Length - 1) {}
Try and avoid using dynamic arrays though. A generic List(Of T)
is much more flexible
尽量避免使用动态数组。泛型List(Of T)
更灵活