C# 和 VB.Net 中数组的起始索引

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

Starting Index of Arrays in C# and VB.Net

c#arraysvb.net

提问by Sunil

Have a look at the following code.,

看看下面的代码。,

C#

C#

 string[] testString = new string[jobs.Count];

Equivalent VB.Net

等效VB.Net

Dim testString() As String = New String(jobs.Count - 1) {}

Why it is taking 'jobs.Count - 1' instead 'jobs.Count' in vb.net while creating new arrays?

为什么在创建新数组时在 vb.net 中使用 'jobs.Count - 1' 而不是 'jobs.Count'?

回答by fixagon

In VB.NET the number in the array declaration means "max index", but in C# it means "number of elements"

在 VB.NET 中,数组声明中的数字表示“最大索引”,但在 C# 中表示“元素数”

回答by John Willemse

In C# the array has the number of elements you provide:

在 C# 中,数组具有您提供的元素数量:

string[] array = new string[2]; // will have two element [0] and [1]

In VB.NET the array has the number of elements you provide, plus one (you specify the max index value):

在 VB.NET 中,数组具有您提供的元素数加一(您指定最大索引值):

Dim array(2) As String // will have three elements (0), (1) and (2)

回答by lexeRoy

Because with your C#code sample,

因为使用您的C#代码示例,

string testString = new string[jobs.Count];

That's a constructor of creating an array of string.

这是创建字符串数组的构造函数。

While with the VB.Net example,

使用 VB.Net 示例时,

Dim testString As String = New String(jobs.Count - 1) {}

You are referring with a new Stringobject with length of string declared in the parenthesis.

您正在使用String括号中声明的字符串长度的新对象进行引用。

If you want to create an array of Stringin VB.Net it must be like this:

如果你想String在 VB.Net 中创建一个数组,它必须是这样的:

Dim testString (jobs.Count) As String

see supporting links below: VB.NetC#

请参阅下面的支持链接: VB.Net C#