foreach 循环中的 C# foreach

标签 c#

我没有太多的 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 时,(即使在嵌套它们时)内部 Enumerator 都应该为您“新建”一个新的迭代器,这应该没有任何问题。当您仍在迭代时从集合中添加或删除项目时,就会出现问题...

请记住,在内部 foreach 中,检查以确保您与外部 for each 不在同一个项目上

  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属性做重力和“其他”力的总和?

关于foreach 循环中的 C# foreach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/331607/

相关文章:

c# - 表单例份验证不适用于特定页面

c# - 如果我们从输入中删除所有脚本和 java 单词,我们可以说我们免受 XSS 攻击吗?

c# - Wpf CheckedListbox - 如何获取所选项目

c# - 使用 HttpContent.ReadAsAsync<T> 解析带有一个对象或数组的响应

c# - C#如何调用串口收到的数据

c# - SHA-1 哈希字节数组与文件流

c# - 为什么我们在对象模型项目中需要 GetHashCode() 函数?

c# - 字典或列表的 GetValueOrDefault 或 null 合并

c# - 加号登录 URL 获取请求

c# - 要连接到 Git,Ruby 会比 c# 有优势吗?