简体   繁体   English

循环中的 C# System.OverflowException 错误

[英]C# System.OverflowException Error in loops

I'm trying to simplify someone's coding to let the codes be more readable.我试图简化某人的编码,让代码更具可读性。 When I run the following code, however, I encountered "System.OverFlowException" error.但是,当我运行以下代码时,遇到了“System.OverFlowException”错误。 I run the code in visual studio IDE.我在 Visual Studio IDE 中运行代码。 The function, "Transmit_Data" is used only to store an array of data.函数“Transmit_Data”仅用于存储数据数组。 "TotalIndexToMod" is the array's length, "CurrentLoopIndexCnt" is the current looping index number of "TotalIndexToMod". “TotalIndexToMod”是数组的长度,“CurrentLoopIndexCnt”是“TotalIndexToMod”的当前循环索引号。 Below are the codes (in C#) :以下是代码(在 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;
        }

    }

}

Most probably error occurs in method Convert.ToInt16 .最有可能的错误发生在方法Convert.ToInt16 中 So please make sure that values are not outside the range of the Int16 type.所以请确保值不超出Int16类型的范围。

Please also consider overloaded method WriteLine with format string parameter.还请考虑带有格式字符串参数的重载方法WriteLine In this way the following line of code:这样,下面这行代码:

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

will be look like so:看起来像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM