加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#foreach在foreach循环中

发布时间:2020-12-16 03:27:05 所属栏目:百科 来源:网络整理
导读:我没有太多的C#的经验,所以如果有人可以指出我正确的方向,我会非常感激.我有一个引用一个对象变量的foreach循环.我想在主对象中再次进行一个foreach循环,将当前变量与对象数组中的其余变量进行比较(或执行操作). 我有以下代码: // Integrate forces for eac
我没有太多的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属性重力与“其他”力量的总结?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读