【问题标题】:Add value to new line in array [duplicate]向数组中的新行添加值[重复]
【发布时间】: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";

谢谢

【问题讨论】:

    标签: c# console-application


    【解决方案1】:

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

     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";
    

    【讨论】:

    • 谢谢,这对我有用。
    猜你喜欢
    • 2011-01-01
    • 2012-08-21
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多