首页 > 解决方案 > 循环中的 C# System.OverflowException 错误

问题描述

我正在尝试简化某人的编码以使代码更具可读性。但是,当我运行以下代码时,我遇到了“System.OverFlowException”错误。我在 Visual Studio IDE 中运行代码。函数“Transmit_Data”仅用于存储数据数组。“TotalIndexToMod”是数组的长度,“CurrentLoopIndexCnt”是“TotalIndexToMod”的当前循环索引号。以下是代码(在 C# 中):

int TotalIndexToMod = 28;
int MaxLoopIndexCnt = 16;


for (int mod = 0; mod < TotalIndexToMod; mod++)
{

    int LeftToMod = MaxLoopIndexCnt - CurrentLoopIndexCnt;

    Transmit_Data(mod, LeftToMod);

    CurrentLoopIndexCnt++;

    Console.WriteLine("CurrentIndexToMod / Mod/ Index : " + Convert.ToInt16(mod));
    CurrentIndexToMod = mod;
    Console.WriteLine("CurrentLoopIndexCnt : " + Convert.ToInt16(CurrentLoopIndexCnt));
    Console.WriteLine("MaxLoop : " + Convert.ToInt16(MaxLoop));
    Console.WriteLine("MaxLoopIndexCnt : " + Convert.ToInt16(MaxLoopIndexCnt));


    if (CurrentLoopIndexCnt > MaxLoopIndexCnt)
    {
        CurrentLoopCnt++;

        if (CurrentLoopCnt > MaxLoop) // last loop end
        {
            // byte Mod_State = (byte)(RxMsg.DATA[0] & 0x03);

            if (CurrentIndexToMod == 128)
            {
                //do something
            }
            else
            {
                //do something
            }
        }
        else
        {
            if (CurrentLoopCnt < MaxLoop)
            {
                MaxLoopIndexCnt = 16;
            }
            else if (CurrentLoopCnt == MaxLoop) // last loop
            {
                MaxLoopIndexCnt = SpareMaxLoopIndexCnt;
            }

            CurrentLoopIndexCnt = 1;
        }

    }

}

标签: c#

解决方案


最有可能的错误发生在方法Convert.ToInt16中。所以请确保值不在Int16类型的范围之外。

还请考虑带有格式字符串参数的重载方法WriteLine 。这样下面的代码行:

Console.WriteLine("CurrentIndexToMod / Mod/ Index : " + Convert.ToInt16(mod));

看起来像这样:

Console.WriteLine("CurrentIndexToMod / Mod/ Index : {0}", mod);

推荐阅读