次のコードを考えると、次の例外を回避する方法を知りたいです
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;
}
}
}
私はもともと、2番目のforeachに次のように単純に入れようとしました:
item.z = 3;
しかし、それは次のエラーを引き起こしました:
Cannot modify members of "item" because it is a "foreach iteration"
foreach 内の構造体データを変更できるようにするために一時オブジェクトを作成しようとしましたが、上記の例外が発生します。私の最善の推測は、一時構造体が値自体ではなく元の構造体への参照を保存しているためです。これにより、元の構造体が一時構造体のときに更新されます。
だから私の質問は: この構造体を参照ではなく値で渡すにはどうすればよいですか? または、この問題を回避するためのまったく別の方法はありますか?
助けてくれてありがとう。
編集:すべての回答に感謝します。リストが参照型であることは承知していますが、その場合、参照ではなく値で渡すことはできませんか?