在C#和VB.Net中,数组的起始索引是什么?

7
请看以下代码。 C#
 string[] testString = new string[jobs.Count];

等价的VB.Net代码

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

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

2
请检查您的问题。两个示例都没有意义。它们都没有定义为数组。 - John Willemse
3个回答

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

6

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

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

在VB.NET中,数组的长度为您提供的元素数量加一(您指定最大索引值):
Dim array(2) As String // will have three elements (0), (1) and (2)

2
因为有了你的C#代码示例,
string testString = new string[jobs.Count];

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

而在VB.Net示例中,

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

你正在使用括号中声明的字符串长度来引用一个新的 String 对象。
如果你想在 VB.Net 中创建一个 String 数组,它必须像这样:
Dim testString (jobs.Count) As String

请查看以下相关链接: VB.Net C#


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接