我没有太多的C#的经验,所以如果有人可以指出我正确的方向,我会非常感激.我有一个引用一个对象变量的foreach循环.我想在主对象中再次进行一个foreach循环,将当前变量与对象数组中的其余变量进行比较(或执行操作).
我有以下代码:
我有以下代码:
// Integrate forces for each body. foreach (RigidBodyBase body in doc.Bodies) { // Don't move background-anchored bodies. if (body.anchored) continue; // This is where we will add Each Body's gravitational force // to the total force exerted on the object. // For each other body,get it's point and it's mass. // Find the gravitational force exterted between target body and looped body. // Find distance between bodies. // vector addition // Force = G*mass1*mass2/distance^2 // Find vector of that force. // Add Force to TotalGravityForce // loop until there are no more bodies. // Add TotalGravityForce to body.totalForce }
解决方法
每次执行foreach时,(即使嵌套它们),内部枚举器应该为您新建一个迭代器,不应该有任何问题.当您还在重复添加或删除集合中的项目时,会出现问题…
记住,在内部的foreach,检查,以确保你不在每个外部的相同项目上
foreach( RigidBodyBase body in doc.Bodies) foreach ( RigidBodyBase otherBody in doc.Bodies) if (!otherBody.Anchored && otherBody != body) // or otherBody.Id != body.Id -- whatever is required... // then do the work here
顺便说一句,放这个代码的最好的地方是在RigidBodyBase类的GravityForce属性中,然后你可以写:
foreach (RigidBodyBase body in doc.Bodies) body.TotalForce += body.GravityForce;
虽然这取决于你在这里做什么(移动所有对象?)他们可能会有更多的重构机会…我也会考虑为“其他”力量单独提供一个属性,并且拥有TotalForce属性重力与“其他”力量的总结?