为何变量设为long仍触发OverflowException?求原因解析
问题分析与解决方案
核心原因
你修改了变量numValue的类型为long或double,但解析字符串的核心操作是int.Parse(inputValue)——这个方法的作用是将字符串转换为int类型,而int的取值范围仅为-2147483648到2147483647,输入值"9999999999"远超出这个范围,因此必然触发OverflowException,和numValue的类型没有关系。
解决方案
使用对应类型的Parse方法
如果要将字符串解析为long类型,应该替换为long.Parse(inputValue);若要解析为double,则使用double.Parse(inputValue)。修正后的代码示例:string[] inputValues = new string[] { "3", "9999999999", "0", "2" }; foreach (string inputValue in inputValues) { long numValue = 0; try { numValue = long.Parse(inputValue); // 替换为long.Parse } catch (FormatException) { Console.WriteLine("Invalid readResult. Please enter a valid number."); } catch (OverflowException) { Console.WriteLine("The number you entered is too large or too small."); } catch (Exception ex) { Console.WriteLine(ex.Message); } }推荐使用TryParse方法(更健壮)
TryParse不会抛出异常,而是通过返回值判断解析是否成功,避免了异常处理的开销,示例:string[] inputValues = new string[] { "3", "9999999999", "0", "2" }; foreach (string inputValue in inputValues) { if (long.TryParse(inputValue, out long numValue)) { // 解析成功,可在此处使用numValue } else { Console.WriteLine("Invalid number or number out of range."); } }
内容的提问来源于stack exchange,提问作者tanzeel ahmed shaikh
相关产品推荐
相关产品推荐

