VB.NET如何声明已知长度的新空数组

时间:2022-09-29 21:37:19

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.

工作,但不是我想要的,因为我想分离数组的声明和初始化。

3 个解决方案

#1


35  

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) {}

#2


8  

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)

#3


3  

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

尽量避免使用动态数组。通用列表(Of T)更灵活

#1


35  

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) {}

#2


8  

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)

#3


3  

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

尽量避免使用动态数组。通用列表(Of T)更灵活