如何修改foreach循环内的foreach迭代变量? [英] How to modify a foreach iteration variable from within foreach loop?

查看:759
本文介绍了如何修改foreach循环内的foreach迭代变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 项目[,] array = new Item [w,h]; //类Item的二维数组
// w,h在编译时是未知的。
foreach(数组中的元素)
{
item = new Item();

$ / code>

...我得到无法分配给'item '因为它是一个'foreach迭代变量'



不过,我想这样做。



这个想法是为现有项目分配默认的 Item 类值。解决方案

好的,现在我们已经知道了您的 ,而不是如何实现它了,回答您的问题要容易得多:您不应该使用 foreach 循环。 foreach 是从集合中读取项目 - 不改变集合的内容。 C#编译器将迭代变量设置为只读是一件不错的工作,否则它可以让您在不更改集合的情况下更改变量的值。 (必须有更多的重大更改,以允许更改反映...)

我怀疑你只是想:


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





$ b $ p

假设它是一个矩形数组(物品[,] )。如果它是一个 Item [] [] 那么它是一个数组的数组,你可能会稍有不同 - 很可能用 foreach <

$ foreach(数组中的var子数组)
{
for(int i = 0; i< subarray.Length; i ++)
{
subarray [i] = new Item();
}
}


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.

解决方案

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

这篇关于如何修改foreach循环内的foreach迭代变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆