gpt4 book ai didi

C# Foreach 和 for 的区别(不是性能)

转载 作者:太空狗 更新时间:2023-10-29 22:20:42 24 4
gpt4 key购买 nike


前段时间我读到 foreach 与对象的“副本”一起工作,因此它可以用于信息检索而不是更新。我不明白,因为完全有可能遍历类列表并更改其字段。谢谢!

最佳答案

可能已经读到的是,您不能在使用 foreach 迭代集合时修改它,而您可以(如果您小心的话)使用 for 循环。例如:

using System;
using System.Collections.Generic;

class Test
{
static void Main()
{
var list = new List<int> { 1, 4, 5, 6, 9, 10 };


/* This version fails with an InvalidOperationException
foreach (int x in list)
{
if (x < 5)
{
list.Add(100);
}
Console.WriteLine(x);
}
*/

// This version is okay
for (int i = 0; i < list.Count; i++)
{
int x = list[i];
if (x < 5)
{
list.Add(100);
}
Console.WriteLine(x);
}
}
}

如果那不是您指的是什么,请提供更多详细信息 - 如果您不确切知道它说的是什么,就很难解释您所读的内容。

关于C# Foreach 和 for 的区别(不是性能),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3896063/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com