【发布时间】:2021-04-05 15:23:16
【问题描述】:
如何在数组中添加新行?该数组当前为空。
我试过了,但是没用
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;
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");
如果你坚持在动态中改变数组的长度,你必须放这样的东西(注意,数组不是集合type 旨在改变其长度):
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";
【讨论】: