鉴于以下代码,我很想知道如何避免以下异常
System.InvalidOperationException was unhandled
Message=Collection was modified; enumeration operation may not execute.
Source=mscorlib
StackTrace:
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
at System.Collections.Generic.List`1.Enumerator.MoveNext()
at PBV.Program.Main(String[] args) in C:\Documents and Settings\tmohojft\Local Settings\Application Data\Temporary Projects\PBV\Program.cs:line 39
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PBV
{
class Program
{
struct structItem
{
public int y { get; set; }
public int z { get; set; }
}
struct testStruct
{
public int x { get; set; }
public List<structItem> items { get; set; }
}
static void Main(string[] args)
{
testStruct a = new testStruct();
structItem b = new structItem();
for (byte i = 0; i <= 10; i++) {
b.y = i;
b.z = i * 2;
a.items = new List<structItem>();
a.items.Add(b);
}
testStruct c = new testStruct();
c = a;
int counter = 0;
//exception thrown on line below
foreach (var item in a.items) {
structItem d = item;
d.z = 3;
c.items[counter] = d;
counter++;
}
a = c;
}
}
}
我最初试图简单地将以下内容放在第二个 foreach 中:
item.z = 3;
但这导致了以下错误:
Cannot modify members of "item" because it is a "foreach iteration"
我试图创建一个临时对象以便能够修改 foreach 中的结构数据,但我收到了上面的异常。我最好的猜测是因为我的临时结构正在保存对原始结构的引用而不是值本身 - 这导致我的原始结构在我的临时结构被更新时被更新。
所以我的问题是: 我如何通过值而不是引用传递这个结构?还是有完全不同的方法来解决这个问题?
在此先感谢您的帮助。
编辑:感谢所有的答案家伙。我知道该列表是一个引用类型,但这是否使得不可能通过值而不是引用传递呢?