将值添加到数组中的新行

Add value to new line in array

如何向数组添加新行?该数组当前为空。

我试过了,但没用

string[] testarray;
testarray[0] = "Lorem ipsum dolor sit amet";
testarray[1] = "example text 1";

int i = testarray.Length;
i++;
testarray[i] = "example text 2";

谢谢

您可以尝试初始化包含所需项目的数组:

 string[] testarray = new string[] {
   "Lorem ipsum dolor sit amet",
   "example text 1",
   "example text 2",  
 };

或在动态中使用List<string>Add项:

 List<string> testArray = new List<string>();

 testArray.Add("Lorem ipsum dolor sit amet"); 
 testArray.Add("example text 1");

 ...

 testArray.Add("example text 2");

如果你坚持数组在动态中改变它的长度,你必须像这样放置(注意,数组是不是设计来改变其长度的集合类型):

 string[] testarray = new string[0];

 ...

 // recreates testarray with longer Length
 Array.Resize(ref testarray, testarray.Length + 1);
 // put the value at the last cell
 testarray[testarray.Length - 1] = "Lorem ipsum dolor sit amet";

 ...
 
 Array.Resize(ref testarray, testarray.Length + 1);

 testarray[testarray.Length - 1] = "example text 1";

 ...
 
 Array.Resize(ref testarray, testarray.Length + 1);

 testarray[testarray.Length - 1] = "example text 2";