Okay, now that we know your aim instead of how you were trying to achieve it, it's much easier to answer your question: you shouldn't be using a foreach
loop. foreach
is about reading items from a collection - not changing the contents of a collection. It's a good job that the C# compiler makes the iteration variable read-only, otherwise it would have let you change the value of the variable without that actually changing the collection. (There'd have to be more significant changes to allow changes to be reflected...)
I suspect you just want:
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
array[i, j] = new Item();
}
}
That's assuming it's a rectangular array (an Item[,]
). If it's an Item[][]
then it's an array of arrays, and you'd handle that slightly differently - quite possibly with a foreach
for the outer iteration:
foreach (var subarray in array)
{
for (int i = 0; i < subarray.Length; i++)
{
subarray[i] = new Item();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…