string.split 方法不需要初始化数组

Initializing an array is not needed with string.split method

有人可以解释一下为什么示例 1 给出了 NullReferenceException 而示例 2 工作正常

   Dim teachers As String()
   Dim Paragraph as string = "one,two"

示例 1

teachers(0) = "Mostafa"
teachers(1) = "Lina"

示例 2

teachers = paragraph.Split(",")

因为您从未给出数组的大小,所以无法为所需的数组长度初始化内存。因此,由于没有初始化,array(0) 将为空。在第二种情况下,赋值会自动将某些内存初始化为数组,因为 String.Split 总是 returns 数组。

首先teachers是一个字符串数组。

Dim teachers As String() 声明了您的字符串数组,但没有指定数组中有多少项或初始化其中的任何一项(此时它是一个 Null 引用)

因此尝试将字符串分配给数组中的项目失败(带有 NullReferenceException),因为它未被初始化:

teachers(0) = "Mostafa" 'Fails
teachers(1) = "Lina"    'Also fails

String.Split 是一个“Returns a string array”的函数,所以当你调用它时,Null Reference 替换为对字符串数组的引用由 String.Split 函数创建,所以这个有效:

teachers = "Mostafa,Lina".Split(","c)

或者你可以用一行声明初始化字符串数组:

Dim teachers As String() = {"Mostafa", "Lina"}