VB.NET空字符串数组

Yon*_*ahW 48 .net vb.net arrays

如何创建一个空的一维字符串数组?

Mar*_*ett 39

VB 在数组声明中0索引的,所以类似的东西Dim myArray(10) as String给你11个元素.从C语言翻译时,这是一个常见的错误.

因此,对于一个空数组,以下任何一个都可以工作:

Dim str(-1) as String ' -1 + 1 = 0, so this has 0 elements
Dim str() as String = New String() { } ' implicit size, initialized to empty
Run Code Online (Sandbox Code Playgroud)

  • 我总是将Dim str()作为String = New String(){},因为我觉得这是查看它是一个EMPTY字符串数组"{}"的最佳方式 (3认同)
  • Mark,Dim str(0)生成一个长度为1且在索引0处为NULL的数组.第二个,Dim str()... {}生成一个长度为零的空数组,如YonahW所需. (2认同)

小智 35

Dim strEmpty(-1)As String

  • 更新......我们发现以下内容相同且仪式较少:Dim myArray()= New String(){} (10认同)
  • Upvote因为它是正确的.但是,为了清楚起见,我更喜欢Dim strEmpty()As String = New String(){},因为Mark提供并且SoMoS赞同.但是,Mark描述了两种不相同的技术......请参阅评论. (8认同)
  • 一个简单的Dim empty As String = {}是最优雅的版本 (2认同)

Joe*_*orn 8

您创建的数组Dim s(0) As String 不是EMPTY

在VB.Net中,您在数组中使用的下标是最后一个元素的索引.VB.Net默认开始索引为0,因此你有一个已经有一个元素的数组.

你应该尝试使用System.Collections.Specialized.StringCollection或(甚至更好)System.Collections.Generic.List(Of String).它们与字符串数组几乎完全相同,除非它们更适合添加和删除项目.说实话:你很少会创建一个字符串数组而不想添加至少一个元素.

如果你真的想要一个空字符串数组,请按如下方式声明:

Dim s As String()
Run Code Online (Sandbox Code Playgroud)

要么

Dim t() As String
Run Code Online (Sandbox Code Playgroud)

  • Joel,这不提供请求的行为.这些中的每一个,t和s都是Nothing.YonahW想要一个GR8DA解决方案提供的空数组,虽然我更喜欢:Dim strEmpty()As String = New String(){} (2认同)

小智 8

您不必包含两次String,也不必使用New.
以下任何一种都可以工作......

Dim strings() as String = {}
Dim strings as String() = {}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ryk 7

就像是:

Dim myArray(9) as String
Run Code Online (Sandbox Code Playgroud)

会给你一个10个String引用的数组(每个引用都指向Nothing).

如果您在声明时不确定大小,可以声明一个这样的String数组:

Dim myArray() as String
Run Code Online (Sandbox Code Playgroud)

然后你可以将它指向一个大小合适的字符串数组:

ReDim myArray(9) as String
Run Code Online (Sandbox Code Playgroud)

如果您不知道总大小并且需要动态填充它,ZombieSheep是关于使用List的.在VB.NET中将是:

Dim myList as New List(Of String)
myList.Add("foo")
myList.Add("bar")
Run Code Online (Sandbox Code Playgroud)

然后从该列表中获取一个数组:

myList.ToArray()
Run Code Online (Sandbox Code Playgroud)

@标记

谢谢你的纠正.