我对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
}
Run Code Online (Sandbox Code Playgroud)
Cha*_*ana 17
每次执行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
Run Code Online (Sandbox Code Playgroud)
顺便说一句,放置此代码的最佳位置是在RigidBodyBase类的GravityForce属性中,然后你可以写:
foreach (RigidBodyBase body in doc.Bodies)
body.TotalForce += body.GravityForce;
Run Code Online (Sandbox Code Playgroud)
虽然取决于你在这里所做的事情(移动所有对象?),但他们可能更有机会进行重构......我还考虑为"其他"部队提供单独的属性,并让TotalForce Property执行重力和"其他"力量的总和?