如何在c#中将foreach循环转换为for循环

时间:2010-06-24 05:14:24

标签: c#-4.0

foreach (Process newprcs in oPrcs)
 {
  newprocid = (UInt32)newprcs.Id;
  if (!oNewProcs.Contains(newprocid))  //checking process id contain or not
    {
      oNewProcs.Add(newprocid);
      // MessageBox.Show(newprocid.ToString());
      uIdOfProcess = newprocid;
      //MessageBox.Show(uIdOfProcess.ToString(),"ProcessId");
      CInjector.HookingAPI(uIdOfProcess, "HookPrintAPIs.dll");
    }
}

2 个答案:

答案 0 :(得分:8)

这取决于oPrcs的类型。如果它是Process[]那么它将是:

for (int i = 0; i < oPrcs.Length; i++)
{
    Process newprcs = oPrcs[i];
    ...
}

否则,如果oPrcs的类型实现了IEnumerable<Process>(它确实没有拥有,但通常会这样做),你会得到:

using (IEnumerator<Process> iterator = oPrcs.GetEnumerator())
{
    while (iterator.MoveNext())
    {
        Process newprcs = iterator.Current;
        ...
    }
}

说了这么多,我通常不会foreach循环转换为for循环......

答案 1 :(得分:4)

假设oPrcsIList<Process>(因此它具有Count属性,并且可以通过索引访问项目):

for (int i = 0; i < oPrcs.Count; i++)
{
    Process newprcs = oPrcs[i];
    if (!oNewProcs.Contains(newprocid))  //checking process id contain or not
    {
        oNewProcs.Add(newprocid);
        // MessageBox.Show(newprocid.ToString());
        uIdOfProcess = newprocid;
        //MessageBox.Show(uIdOfProcess.ToString(),"ProcessId");
        CInjector.HookingAPI(uIdOfProcess, "HookPrintAPIs.dll");
    }
}