【问题标题】:How can I initialize a IList<IList<string>>?如何初始化 IList<IList<string>>?
【发布时间】:2012-02-27 19:57:51
【问题描述】:

试过了:

IList<IList<string>> matrix = new List<new List<string>()>();

但我不能。我该怎么做?我需要一个字符串矩阵...

【问题讨论】:

    标签: c# arrays list matrix initialization


    【解决方案1】:

    试试这个

        IList<IList<string>> matrix = new List<IList<string>>();
    

    【讨论】:

      【解决方案2】:

      你需要:

      IList<IList<string>> matrix = new List<IList<string>>();
      

      但是您可以发生始终为每个元素添加List&lt;string&gt;

      这不起作用的原因:

      // Invalid
      IList<IList<string>> matrix = new List<List<string>>();
      

      这样写是否合理:

      // string[] implements IList<string>
      matrix.Add(new string[10]);
      

      ...但这会违反列表真的List&lt;List&lt;string&gt;&gt;这一事实 - 它必须包含List&lt;string&gt;值,而不仅仅是任何 @987654327 @... 而我在顶部的声明只是创建了一个List&lt;IList&lt;string&gt;&gt;,因此您可以向它添加一个字符串数组而不会破坏类型安全。

      当然,您可以改为在声明中使用具体类型:

      IList<List<string>> matrix = new List<List<string>>();
      

      甚至:

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

      【讨论】:

        【解决方案3】:

        这行得通 - 您无法按照您尝试的方式初始化泛型类型参数:

        IList<IList<string>> matrix = new List<IList<string>>();
        

        虽然,内部的IList&lt;string&gt; 将是null。要初始化它,您可以执行以下操作:

        matrix.Add(new List<string>());
        

        【讨论】:

          【解决方案4】:

          如果矩阵是常数大小的数组更合适

          string[][] matrix = new string[size];
          matrix[0] = new string[5];
          matrix[1] = new string[8];
          matrix[2] = new string[7];
          

          如果是矩形

          string[,] matrix = new string[sizex,sizey];
          

          【讨论】:

          • 我不知道初始大小...应该是动态的 :)
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-27
          • 1970-01-01
          相关资源
          最近更新 更多