簡體   English   中英

如何從 foreach 循環中修改 foreach 迭代變量?

[英]How to modify a foreach iteration variable from within foreach loop?

當我嘗試這樣做時...

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

...我得到Cannot assign to 'item' because it is a 'foreach iteration variable'

盡管如此,我還是想這樣做。

這個想法是將默認Item類值分配給現有項目。

好的,既然我們知道你的目標而不是你想要實現它的目的,那么回答你的問題要容易得多:你不應該使用foreach循環。 foreach是關於從集合中讀取項目 - 而不是更改集合的內容。 這是一個很好的工作,C#編譯器使迭代變量只讀,否則它會讓你改變變量的值而不實際改變集合。 (必須有更重要的變化才能反映出變化......)

我懷疑你只想要:

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用於外部迭代:

foreach (var subarray in array)
{
    for (int i = 0; i < subarray.Length; i++)
    {
        subarray[i] = new Item();
    }
}

不知道尺寸不是問題:

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

看起來你正在嘗試初始化數組。 你不能這樣做 相反,您需要通過索引遍歷數組。

要初始化給定二維數組的元素,請嘗試以下方法:

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

你可以使用normal for循環。

只需使用 List.Foreach 即可。 很簡單。 如果需要,您可以從循環列表中刪除/刪除項目。

對於給我否定的家伙。 去他媽的自己。

  mList.ForEach(mov =>
  {
         if (mov.EndsWith("."))
              mov = mov + "m";                                                      
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM