如何调试C#中的System.ArgumentOutOfRangeException异常?代码报错求助
解决字符串操作引发的System.ArgumentOutOfRangeException异常
兄弟,我太懂这个坑了!你写的这段处理样本序列的代码,测试时触发的System.ArgumentOutOfRangeException,几乎可以肯定是字符串截取操作的边界没校验到位导致的。咱们一步步来搞定它:
问题重现
你遇到的错误提示:
System.ArgumentOutOfRangeException: 'Index and length must refer to a place within the string. Parameter name: length'
你的代码片段:
class Program { static void Main(string[] args) { Console.WriteLine(GetSample()); Console.ReadKey(); } public static int GetSample() { // 你的核心逻辑实现(这里虽未完全展示,但问题大概率出在字符串截取相关代码上) } }
问题根源
这个异常的触发场景只有两种:
- 调用
Substring(或同类字符串截取方法)时,起始索引startIndex大于等于字符串总长度 - 起始索引加上截取长度
length的总和,超过了字符串的实际长度
举个直观的错误例子:
string testStr = "abcde"; // 长度为5 // 错误:起始索引3 + 长度3 =6 >5,超出范围 string wrongSub = testStr.Substring(3,3); // 错误:起始索引5等于字符串长度,超出范围 string anotherWrong = testStr.Substring(5);
修复方案
1. 给字符串截取加严格的边界校验
在所有调用Substring的地方,先判断参数是否合法,再执行截取:
public static int GetSample() { // 假设originalStr是原始样本字符串,newStr是新样本字符串 string originalStr = "你的原始样本内容"; string newStr = "你的新样本内容"; int startIndex = 0; // 你计算出的起始位置 int takeLength = 0; // 你计算出的要截取的长度 // 关键:先做边界校验 if (startIndex >=0 && startIndex < originalStr.Length && takeLength >=0 && startIndex + takeLength <= originalStr.Length) { string targetFragment = originalStr.Substring(startIndex, takeLength); // 后续的匹配、计算逻辑 } else { // 处理参数非法的情况:比如返回合理默认值,或者抛出更友好的提示 throw new ArgumentException("计算出的截取参数超出原始样本字符串范围,请检查序列匹配逻辑"); } // 你的其他逻辑... return 0; }
2. 针对样本序列场景的额外注意点
因为你是在找要插入第一个序列的最小连续片段,还要注意:
- 当新样本的长度大于原始样本时,要单独处理(比如直接返回新样本长度,或者做特殊判断)
- 计算片段起始位置和长度时,确保不会出现负数或者超过字符串长度的数值
内容的提问来源于stack exchange,提问作者SeanleArch
相关产品推荐
相关产品推荐

