How to modify a foreach iteration variable from within foreach loop?

穿精又带淫゛_ 提交于 2019-12-18 18:53:59

问题


When I try to do this...

Item[,] array = new Item[w, h];  // Two dimensional array of class Item, 
                                 //   w, h are unknown at compile time.
foreach(var item in array)
{
    item = new Item();
}

...I get Cannot assign to 'item' because it is a 'foreach iteration variable'.

Still, I'd like to do that.

The idea is to assign default Item class values to existing item.


回答1:


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();
    }
}



回答2:


Not knowing the size isn't a problem:

for (int i = 0; i < twoDimArray.GetLength(0); i++)
{
    for (int j = 0; j < twoDimArray.GetLength(1); j++)
    {
        twoDimArray[i, j] = ...
    }
}



回答3:


It looks like you're trying to initialize the array. You can't do that this way. Instead, you need to loop through the array by index.

To initialize the elements of a given two-dimensional array, try this:

for (int d = 0; d < array.GetLength(0); d++)
{
    for (int i = 0; i < array.GetLength(1); i++)
    {
        array[d, i] = new Item();
    }
}



回答4:


You can use normal for loop for that.



来源:https://stackoverflow.com/questions/11810794/how-to-modify-a-foreach-iteration-variable-from-within-foreach-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!