2012-02-06 136 views

回答

12

您將需要:

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]); 

...但是這將違反事實列表是真的 a List<List<string>> - 它必須包含List<string>的值,而不僅僅是任何IList<string> ...而我在上面的聲明只是創建了一個List<IList<string>>,所以你可以給它添加一個字符串數組沒有分類型安全。

當然,你可以變化使用的具體類型,在你的聲明,而不是:

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>>(); 
+1

我的回答得到了skeeted: D – 2012-02-06 10:15:54

1

這將工作 - 你不能初始化通用type參數你試過的方式:

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

雖然,t他內心IList<string>將是null。要初始化它,你可以做到以下幾點:

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

@Downvoter - 謹慎評論? – Oded 2012-02-06 10:27:52

1

如果矩陣是恆定的大小陣列是一個更適合

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]; 
+0

我不知道初始大小...應該是dinamic :) – markzzz 2012-02-06 15:24:48