c# - 循环中的 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;
}
}
}
解决方案
最有可能的错误发生在方法Convert.ToInt16中。所以请确保值不在Int16类型的范围之外。
还请考虑带有格式字符串参数的重载方法WriteLine 。这样下面的代码行:
Console.WriteLine("CurrentIndexToMod / Mod/ Index : " + Convert.ToInt16(mod));
看起来像这样:
Console.WriteLine("CurrentIndexToMod / Mod/ Index : {0}", mod);
推荐阅读
- visual-studio-code - 自定义自动完成键
- python - Python Pandas Dataframe.at 函数
- java - 无法将 shottbuffer 深度图像转换为图片格式
- python - seaborn.set_theme() 方法不起作用
- ios - 混合 CocoaPods、SPM 和多个目标
- mysql - Mysql request group by 将其他结果保留在最后
- angular - 更新数组时 ngOnChanges 的问题
- asp.net - IIS 下载应用程序而不是显示
- python - 层顺序的输入与层不兼容:LSTM中的形状错误
- python - 我正在尝试使用 matplotlib 在 python 中将散点图绘制到我的 3d 连续图上