【问题标题】:Options for initializing a string array [duplicate]初始化字符串数组的选项[重复]
【发布时间】:2010-12-03 01:20:50
【问题描述】:

初始化string[]对象时有哪些选项?

【问题讨论】:

    标签: c# arrays initialization


    【解决方案1】:

    您有多种选择:

    string[] items = { "Item1", "Item2", "Item3", "Item4" };
    
    string[] items = new string[]
    {
      "Item1", "Item2", "Item3", "Item4"
    };
    
    string[] items = new string[10];
    items[0] = "Item1";
    items[1] = "Item2"; // ...
    

    【讨论】:

    • 不要忘记string[] items = { "Item1", "Item2", "Item3", "Item4" }; 快捷方式。
    【解决方案2】:

    基本:

    string[] myString = new string[]{"string1", "string2"};
    

    string[] myString = new string[4];
    myString[0] = "string1"; // etc.
    

    高级: 来自列表

    list<string> = new list<string>(); 
    //... read this in from somewhere
    string[] myString = list.ToArray();
    

    来自字符串集合

    StringCollection sc = new StringCollection();
    /// read in from file or something
    string[] myString = sc.ToArray();
    

    【讨论】:

    • 有人可以在上面添加一个“来自列表”的示例,但是对于将 2 个列表的内容加载到二维数组(不是锯齿状,即 double[,])的情况?
    【解决方案3】:
    string[] str = new string[]{"1","2"};
    string[] str = new string[4];
    

    【讨论】:

      猜你喜欢
      • 2015-07-25
      • 2013-07-05
      • 2016-11-20
      • 1970-01-01
      • 2011-12-11
      • 1970-01-01
      • 2014-12-30
      • 1970-01-01
      相关资源
      最近更新 更多