2012-05-01 22 views
1

在一類,CharList,我有一個私人表(表<名單<NewChar> >)和一對索引的:自定義索引器「不能分配給」?

private List<List<NewChar>> _charList; 

// ... 

public NewChar this[Int32 inner, Int32 outer] 
{ 
    get 
    { 
     if (inner < 0 || inner >= _charList.Count || 
      outer < 0 || outer >= _charList[inner].Count) 
      throw new ArgumentException("NewCharList indexer[,]: Invalid index!"); 

     return _charList[inner][outer]; 
    } 
} 

public List<NewChar> this[Int32 index] 
{ 
    get 
    { 
     if (index < 0 || index > MaxCharListIndex) 
      throw new ArgumentException("NewCharList indexer[]: Invalid index"); 
     List<NewChar> ret = new List<NewChar>(_charList[index].Count); 

     for (int i = 0; i < _charList[index].Count; i++) 
      ret.Add(_charList[index][i]); 

     return ret; 
    } 
} 

在測試代碼(其他類),如果我叫

charList[0] = null; 

我得到一個編譯錯誤「屬性或索引XXX不能被分配到 - 它是隻讀的」,但如果我叫

charList[0][0] = new NewChar(22,22); 

編譯器將允許它,但值不會改變。 爲什麼會讓我分配給第二個? 我不能爲了我的生活而弄明白,這讓我發瘋。當你寫這個(即使它不改變的值)

回答

3

charList[0][0] = new NewChar(22,22); 

你實際上並沒有使用你的第一個索引,但你的第二個。這更像是:

List<NewChar> temp = charList[0]; 
temp[0] = new NewChar(22,22); 

使用你的第一個索引的語法是:

charList[0, 0] = new NewChar(22,22); 

然而,這將提供你現在正在接受相同的編譯器錯誤,因爲你沒有一個二傳手在該索引的屬性上。

在一個側面說明,您可以通過使用List<T>.AddRange甚至List<T>構造函數,它接受一個IEnumerable<T>,簡化你的第二個索引屬性的實現,即:

get 
{ 
    if (index < 0 || index > MaxCharListIndex) 
     throw new ArgumentException("NewCharList indexer[]: Invalid index"); 
    return new List<NewChar>(_charList[index]); 
} 
0

我想你沒有setthis[int]索引:

public List<NewChar> this[Int32 index] 
{ 
    get 
    { 
     //...... 
     return ret; 
    } 
    //set { /*YOU DON'T HAVE THIS METHOD*/} 
} 
+0

對不起 - 我忘記提及這是我想要的行爲(索引者不改變這個列表) - 只是第二個會,我想知道爲什麼。 – Richard

相關問題