如何从 foreach 循环中修改 foreach 迭代变量?

How to modify a foreach iteration variable from within foreach loop?(如何从 foreach 循环中修改 foreach 迭代变量?)
本文介绍了如何从 foreach 循环中修改 foreach 迭代变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试这样做时......

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

...我得到 无法分配给item",因为它是foreach 迭代变量".

不过,我还是想这样做.

Still, I'd like to do that.

想法是将默认的 Item 类值分配给现有项目.

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

推荐答案

好的,现在我们知道您的目标,而不是您尝试实现它的方式,回答您的问题要容易得多:你不应该使用 foreach 循环.foreach 是关于从集合中读取 项 - 不更改集合的内容.C# 编译器将迭代变量设置为只读是一项很好的工作,否则它会让您更改 variable 的值而不会实际更改集合.(必须进行更重大的更改才能反映更改...)

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...)

我怀疑你只是想要:

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

假设它是一个矩形数组(一个Item[,]).如果它是一个 Item[][] 那么它是一个数组数组,你会稍微不同地处理它 - 很可能使用 foreach 进行外部迭代:

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 迭代变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)