VB.NET 中声明数组的不同方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16630679/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 13:38:34  来源:igfitidea点击:

Different ways of declaring arrays in VB.NET

arraysvb.net

提问by Enrique

In VB.NET, is there any difference between the following ways of declaring arrays?

在VB.NET中,以下声明数组的方式有什么区别吗?

- Dim cargoWeights(10) as Double

- cargoWeights = New Double(10) {}

' These are two independent statements. They are not supposed to execute one after the other.

'这是两个独立的声明。他们不应该一个接一个地执行。

As far as I know, the first one just declares an array variable that holds the value 'Nothing' until some array object is assigned to it. In other words, it is not initialized yet.

据我所知,第一个只是声明了一个数组变量,该变量保存值“Nothing”,直到将某个数组对象分配给它。换句话说,它还没有被初始化。

But what about the second statement? Does the "=" sign means the variable is already being initialized and won't hold 'Nothing'? Is it going to point to an one-dimensional array of eleven default Double values (0.0)?

但是第二个语句呢?“=”符号是否表示该变量已经被初始化并且不会保存“Nothing”?它会指向一个包含 11 个默认 Double 值 (0.0) 的一维数组吗?

EDIT:

编辑:

According to MSDN website:

根据 MSDN 网站:

The following example declares an array variable that does not initially point to any array.

Dim twoDimStrings( , ) As String

(...) the variable twoDimStrings has the value Nothing.

下面的示例声明了一个最初不指向任何数组的数组变量。

Dim twoDimStrings( , ) As String

(...) 变量 twoDimStrings 的值为 Nothing。

Source: http://msdn.microsoft.com/en-us/library/18e9wyy0(v=vs.80).aspx

来源:http: //msdn.microsoft.com/en-us/library/18e9wyy0(v=vs.80).aspx

回答by ajakblackgoat

Both Dim cargoWeights(10) as Doubleand cargoWeights = New Double(10) {}will actually initialize an array of doubles with each items set to default type value, which in this case, 0.0. (Or Nothing if Stringdata type)

二者Dim cargoWeights(10) as DoublecargoWeights = New Double(10) {}实际上将初始化双打的设置为默认类型值各项目中,阵列在这种情况下,0.0。(或者如果String数据类型为空)

The difference between the two syntax is that, the 2nd one you can init the value of each items in the array to different from default value, like:

两种语法的区别在于,第二种语法可以将数组中每个项目的值初始化为与默认值不同的值,例如:

cargoWeights = New Double(10) {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}

To declare uninitialized array, use Dim cargoWeights() As Doubleor cargoWeights = New Double() {}.

要声明未初始化的数组,请使用Dim cargoWeights() As DoublecargoWeights = New Double() {}