【发布时间】:2012-02-27 19:57:51
【问题描述】:
试过了:
IList<IList<string>> matrix = new List<new List<string>()>();
但我不能。我该怎么做?我需要一个字符串矩阵...
【问题讨论】:
标签: c# arrays list matrix initialization
试过了:
IList<IList<string>> matrix = new List<new List<string>()>();
但我不能。我该怎么做?我需要一个字符串矩阵...
【问题讨论】:
标签: c# arrays list matrix initialization
试试这个
IList<IList<string>> matrix = new List<IList<string>>();
【讨论】:
你需要:
IList<IList<string>> matrix = new List<IList<string>>();
但是您可以发生始终为每个元素添加List<string>。
这不起作用的原因:
// Invalid
IList<IList<string>> matrix = new List<List<string>>();
这样写是否合理:
// string[] implements IList<string>
matrix.Add(new string[10]);
...但这会违反列表真的是List<List<string>>这一事实 - 它必须包含List<string>值,而不仅仅是任何 @987654327 @... 而我在顶部的声明只是创建了一个List<IList<string>>,因此您可以向它添加一个字符串数组而不会破坏类型安全。
当然,您可以改为在声明中使用具体类型:
IList<List<string>> matrix = new List<List<string>>();
甚至:
List<List<string>> matrix = new List<List<string>>();
【讨论】:
这行得通 - 您无法按照您尝试的方式初始化泛型类型参数:
IList<IList<string>> matrix = new List<IList<string>>();
虽然,内部的IList<string> 将是null。要初始化它,您可以执行以下操作:
matrix.Add(new List<string>());
【讨论】:
如果矩阵是常数大小的数组更合适
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];
【讨论】: