非常令人困惑的for循环行为

时间:2013-11-29 14:12:03

标签: c#

我遇到这个代码片段的一个非常奇怪的行为。 通常,当声明为16但是离开时,声明不会输入。 在我的情况下,它输入i=16并执行以ArrayOutOfBoundsException结尾的零案例。

每次拨打foo()时,都会重复此行为 对此有任何解释吗?

void foo()
{
  Thread.Sleep(2000);
  try
  {
    for (int i = 0; i < 16; i++)
    {
      #region Switch
        (switch on 0 to 15 and do something unrelated)
      #endregion 
    }
  }
  catch (Exception ex)
  {
    MessageBox.Show("Exception occured: " + ex);
  }
}

enter image description here

1 个答案:

答案 0 :(得分:3)

为什么不循环到你的数组长度?

for (int i = 0; i < array.Length; i++)
{
    //Your secret code here
}

另外,请确保您没有在任何地方更改循环内的i值。

您将永远不会使用此代码获取异常(除非您在循环内修改i),无论数组长度如何。

相关问题