循环内调用Substring报ArgumentOutOfRangeException错误求助
解决Substring引发的ArgumentOutOfRangeException问题
问题根源
你遇到的异常是因为循环中存在部分products[i, 2]的字符串长度小于10,调用Substring(10)时起始索引超出了字符串的有效范围。你单独测试products[7,2]能正常运行,只是因为这个元素的长度刚好满足要求,但其他索引的元素并不符合这个条件。
解决方案
1. 先检查字符串长度再截取
在截取前先判断字符串长度是否足够,避免直接调用Substring引发异常,同时增加数字格式验证:
case "4": int totalQuantity = 0; Console.WriteLine("List of products:"); for (int i = 0; i < countProducts; i++) { string quantityStr = products[i, 2]; // 先检查长度是否满足截取要求 if (quantityStr.Length >= 10) { string justQuantity = quantityStr.Substring(10); // 用TryParse避免格式错误导致的转换异常 if (int.TryParse(justQuantity, out int quantity)) { totalQuantity += quantity; } else { Console.WriteLine($"警告:第{i}个商品的数量格式无效:{quantityStr}"); } } else { Console.WriteLine($"警告:第{i}个商品的数量字符串过短:{quantityStr}"); } // 输出逻辑... } break;
2. 用正则表达式提取数字(更鲁棒)
如果数量是字符串中的纯数字部分,不管它在什么位置,用正则提取更可靠:
// 先在代码顶部引入正则命名空间 using System.Text.RegularExpressions; // 然后在case 4中修改: case "4": int totalQuantity = 0; Console.WriteLine("List of products:"); // 匹配字符串中的连续数字序列 Regex numRegex = new Regex(@"\d+"); for (int i = 0; i < countProducts; i++) { string quantityStr = products[i, 2]; Match match = numRegex.Match(quantityStr); if (match.Success) { int quantity = int.Parse(match.Value); totalQuantity += quantity; } else { Console.WriteLine($"警告:第{i}个商品未找到有效数量:{quantityStr}"); } // 输出逻辑... } break;
3. 排查数组初始化逻辑
你可以先打印所有products[i,2]的内容,找出长度不足的元素,修正数组初始化时的错误:
// 在循环前添加调试代码 for (int i = 0; i < countProducts; i++) { Console.WriteLine($"索引{i}的内容:{products[i,2]},长度:{products[i,2].Length}"); }
通过这段代码你能清楚看到哪个元素不符合预期,进而修正初始化时的赋值逻辑。
内容的提问来源于stack exchange,提问作者bad lise
相关产品推荐
相关产品推荐

