Custom indexer “cannot be assigned to”?
質問
In a class, CharList, I have a private list (List<List<NewChar>>) and a couple of indexers:
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;
}
}
In the testing code (another class), if I call
charList[0] = null;
I get a compiler error "Property or indexer xxx cannot be assigned to - it is read-only", but if I call
charList[0][0] = new NewChar(22,22);
the compiler will allow it, though the value won't change. Why will it let me assign to the second? I can't for the life of me figure it out, and it's driving me mad! (Even though it doesn't change the value)
解決
When you write this:
charList[0][0] = new NewChar(22,22);
You're not actually using your first indexer, but your second. This is more like:
List<NewChar> temp = charList[0];
temp[0] = new NewChar(22,22);
The syntax to use your first indexer would be:
charList[0, 0] = new NewChar(22,22);
However, this will provide the same compiler error you are receiving now, as you do not have a setter on that indexed property.
On a side note, you can simplify your second indexed property implementation by using List<T>.AddRange
or even the List<T>
constructor that accepts an IEnumerable<T>
, ie:
get
{
if (index < 0 || index > MaxCharListIndex)
throw new ArgumentException("NewCharList indexer[]: Invalid index");
return new List<NewChar>(_charList[index]);
}
他のヒント
I think you don't have set
for this[int]
indexer:
public List<NewChar> this[Int32 index]
{
get
{
//......
return ret;
}
//set { /*YOU DON'T HAVE THIS METHOD*/}
}