相关疑难解决方法(0)

为什么C#foreach语句中的迭代变量是只读的?

据我了解,C#的foreach迭代变量是不可变的.

这意味着我不能像这样修改迭代器:

foreach (Position Location in Map)
{
     //We want to fudge the position to hide the exact coordinates
     Location = Location + Random();     //Compiler Error

     Plot(Location);
}
Run Code Online (Sandbox Code Playgroud)

我无法直接修改迭代器变量,而是必须使用for循环

for (int i = 0; i < Map.Count; i++)
{
     Position Location = Map[i];
     Location = Location + Random();

     Plot(Location);        
     i = Location;
}
Run Code Online (Sandbox Code Playgroud)

来自C++背景,我认为foreach是for循环的替代品.但是由于上述限制,我通常会回退使用for循环.

我很好奇,使迭代器不可变的原理是什么?


编辑:

这个问题更多的是一个好奇的问题,而不是一个编码问题.我很欣赏编码答案,但我不能将它们标记为答案.

此外,上面的例子过于简化了.这是我想要做的C++示例:

// The game's rules: 
//   - The "Laser Of Death (tm)" moves around the game board from the
//     start area (index …
Run Code Online (Sandbox Code Playgroud)

c# language-design

35
推荐指数
3
解决办法
2万
查看次数

修改foreach循环内的列表

我有一个类似的结构(但很多更复杂的):

var list = new List<string>();

// .. populate list ..

foreach(var item in list)
{
    DoFunction(list);
}

public void DoFunction(List<string> list)
{
    if(someCondition == true)
    {
        // .. modify list in here ..
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我明白它不可能编辑你正在进行的集合,但如果你必须编辑列表(没有try catch声明),你如何优雅地跳出循环?有没有办法判断列表是否已被编辑?您可以在break;注意到之前快速编辑列表吗?

c# foreach list

17
推荐指数
2
解决办法
4万
查看次数

为什么"带有循环索引的猴子"不好?

史蒂夫麦康奈尔的一个清单项目是你不应该使用循环索引(第16章,第25页,循环索引,PDF格式).

这是直觉上的,并且是我一直遵循的练习,除非我学会了如何在当天编程.

在最近的代码审查中,我发现这个尴尬的循环并立即将其标记为可疑.

        for ( int i=0 ; i < this.MyControl.TabPages.Count ; i++ )
        {
            this.MyControl.TabPages.Remove ( this.MyControl.TabPages[i] );
            i--;
        }
Run Code Online (Sandbox Code Playgroud)

它几乎是有趣的,因为它设法通过将索引保持为零来工作,直到删除所有TabPages.

这个循环可以写成

        while(MyControl.TabPages.Count > 0)
            MyControl.TabPages.RemoveAt(0);
Run Code Online (Sandbox Code Playgroud)

而且由于控制实际上与循环几乎同时写入,它甚至可以写成

        MyControl.TabPages.Clear();
Run Code Online (Sandbox Code Playgroud)

我一直以来受到质疑有关代码审查问题,并发现我的关节为什么它是不好的做法,是没有那么强,因为我会很喜欢.我说很难理解循环的流程,因此难以维护和调试,并且最终在代码的生命周期内更加昂贵.

是否有更好的阐述为什么这是不好的做法?

c# for-loop

16
推荐指数
3
解决办法
2144
查看次数

当它可以被修改时经历一个foreach?

我想在取出foreach循环的成员时执行foreach循环,但这会引发错误.我唯一的想法是在这个循环中创建另一个列表以找到要删除的切片,并循环遍历新列表以从Pizza中删除项目.

foreach(var Slice in Pizza)
{
    if(Slice.Flavor == "Sausage")
    {
        Me.Eat(Slice); //This removes an item from the list: "Pizza"
    }
}
Run Code Online (Sandbox Code Playgroud)

c# foreach

12
推荐指数
2
解决办法
526
查看次数

C#阻止Collection被修改的异常

是否

 foreach(T value in new List<T>(oldList) )
Run Code Online (Sandbox Code Playgroud)

当oldList包含1百万个对象T时危险(代价高昂)?

更常见的是,在枚举期间添加/删除元素时,枚举oldList的最佳方法是什么?

c# collections enumeration

10
推荐指数
2
解决办法
1万
查看次数

在c#中使用foreach循环时修改集合

基本上,我想在foreach循环中删除列表中的项目.我知道在使用for循环时这是可能的,但出于其他目的,我想知道使用foreach循环是否可以实现这一点.

在python中,我们可以通过执行以下操作来实现此目的:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]

for i in a:
    print i

    if i == 1:
        a.pop(1)
Run Code Online (Sandbox Code Playgroud)

这给出了以下输出

>>>1
3
4
5
6
7
8
9
Run Code Online (Sandbox Code Playgroud)

但是当在c#中做类似的事情时,我得到一个InvalidOperationException,我想知道是否有办法解决这个问题,而不仅仅是使用for循环.

我抛出异常时使用的c#代码:

static void Main(string[] args)
  {
  List<string> MyList = new List<string>(new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9"});

  foreach (string Item in MyList)
    {
    if (MyList.IndexOf(Item) == 0)
      {
      MyList.RemoveAt(1);
      }

    Console.WriteLine(Item);
    }
  }
Run Code Online (Sandbox Code Playgroud)

提前致谢

c# python invalidoperationexception

8
推荐指数
2
解决办法
3245
查看次数

使用LINQ从列表中删除特定项

我有一个包含一些对象的列表,并希望使用LINQ删除特定项目但不知道如何做到这一点.

foreach (var someobject in objectList)
{
    if (someobject.Number == 1) // There will only one item where Number == 1.  
    {
        list.remove(someobject)
    } 
}
Run Code Online (Sandbox Code Playgroud)

c# linq

7
推荐指数
1
解决办法
2万
查看次数

List.forEach 无法修改元素?

我正在尝试创建一个列表列表来模仿 Dart 中二维数组的功能,但我在弄清楚如何使其工作时遇到了麻烦。

我最初List.forEach是为了创建列表并填充它们而使用的,但是在每次循环之后,就好像我从未创建过列表一样。下面是代码的样子:

currentMap = new List<List<int>>(height);
currentMap.forEach((e) {
    e = new List<int>(width);
    e.forEach((f) {
        f = 1;
    });
});
Run Code Online (Sandbox Code Playgroud)

打印currentMap结果为null. 这是我现在所拥有的:

currentMap = new List<List<int>>(height);
for(int i = 0; i < height; i++) {
    currentMap[i] = new List<int>(width);
    for(int j = 0; j < width; j++) {
        currentMap[i][j] = 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

这完全符合我的预期。

我知道这可能是一个非常基本的问题,我假设forEach不允许您修改元素,但我想对此进行一些确认,并且 Dart API 文档没有指定除了短语“apples the function f”每个元素......”这对我来说可能不太清楚。

另外,我知道List.filled()构造函数之类的东西——这就是我开始构建其他功能的方式。

编辑:好的,我想我现在明白了。参数是“传递共享”,这意味着对对象的引用进行了复制。这意味着您可以修改参数指向的可变对象的成员(如下所示):

void function(MyObject o) {
    o.x = …
Run Code Online (Sandbox Code Playgroud)

arrays foreach dart

6
推荐指数
1
解决办法
4974
查看次数

迭代过程中收集异常并从该集合中删除项目

我在foreach循环中从ArrayList中删除项目并获得以下异常.

收集被修改; 枚举操作可能无法执行.

如何删除foreach中的项目,

编辑: 可能有一个项目要删除或两个或全部.

以下是我的代码:

/*
 * Need to remove all items from 'attachementsFielPath' which does not exist in names array.
 */

try
{
    string attachmentFileNames = txtAttachment.Text.Trim(); // Textbox having file names.
    string[] names = attachmentFileNames.Split(new char[] { ';' });

    int index = 0;

    // attachmentsFilePath is ArrayList holding full path of fiels user selected at any time.
    foreach (var fullFilePath in attachmentsFilePath)
    {
        bool isNeedToRemove = true;

        // Extract filename from full path.
        string fileName = …
Run Code Online (Sandbox Code Playgroud)

c# c#-3.0 c#-2.0

5
推荐指数
3
解决办法
2676
查看次数

C#列表插入foreach

我有以下循环:

List<Reminders> reminds = new List<Reminders>();
//...
foreach (Reminders remind in reminds)
{
    //....
    reminds.Insert(id, new Reminders() { Title = remind.Title, Content = remind.Content, Checked = true });
}
Run Code Online (Sandbox Code Playgroud)

但是,foreach循环中会发生错误。

foreach (Reminders remind in reminds)
Run Code Online (Sandbox Code Playgroud)

如果我删除该reminds.Insert语句,该错误将不再发生。我正在尝试更新循环内的某些整体foreach。是什么导致错误?

c# foreach insert

5
推荐指数
2
解决办法
9152
查看次数