代码之家  ›  专栏  ›  技术社区  ›  Sunil

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

  •  7
  • Sunil  · 技术社区  · 11 年前

    请查看以下代码。,

    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”?

    3 回复  |  直到 11 年前
        1
  •  15
  •   fixagon    11 年前

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

        2
  •  6
  •   John Willemse    11 年前

    在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)
    
        3
  •  2
  •   roybalderama    11 年前

    因为你的 C# 代码样本,

    string testString = new string[jobs.Count];
    

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

    而对于VB.Net示例,

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

    你指的是一个新的 String 对象,括号中声明的字符串长度为。

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

    Dim testString (jobs.Count) As String
    

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