C#检查变量是否含字符串及文件读取空引用异常求助
解决C#中调用Contains时的NullReferenceException问题
兄弟,你遇到的这个空引用异常原因很明确:当StreamReader.ReadLine()读到文件末尾时会返回null,这时候你直接调用Contains方法,相当于在null对象上调用方法,自然就触发异常了。
给你几个靠谱的解决办法,按你的需求来选:
1. 先检查行是否为null,再判断包含关系
最直接的方式就是在循环里先确认读取到的行不是null,再去判断是否包含"EHRS":
string[] concArray = new string[numLinesConcYr]; int currentIndex = 0; // 用来跟踪数组的存储位置 using (var sr = new StreamReader("你的文件路径.txt")) { string line; // 循环读取每一行,直到返回null(文件读完) while ((line = sr.ReadLine()) != null) { if (line.Contains("EHRS")) { // 注意这里要确保currentIndex不超过数组长度,避免越界 if (currentIndex < concArray.Length) { concArray[currentIndex] = line; currentIndex++; } } } }
2. 用null条件运算符简化判断(C# 6.0+)
如果你的项目用的是C# 6.0及以上版本,可以用?.运算符来简化null检查,它会先判断line是否为null,只有非null时才会调用Contains:
string[] concArray = new string[numLinesConcYr]; int currentIndex = 0; using (var sr = new StreamReader("你的文件路径.txt")) { string line; while ((line = sr.ReadLine()) != null) { // 用?.确保line非null时才调用Contains,结果和true比较 if (line?.Contains("EHRS") == true) { if (currentIndex < concArray.Length) { concArray[currentIndex] = line; currentIndex++; } } } }
3. 更灵活的方案:用List代替固定数组
提前计算numLinesConcYr其实挺麻烦的,万一实际符合条件的行数比你预估的多,还会触发数组越界异常。换成List<string>就没这个问题了,它会自动扩容:
List<string> concList = new List<string>(); using (var sr = new StreamReader("你的文件路径.txt")) { string line; while ((line = sr.ReadLine()) != null) { if (line?.Contains("EHRS") == true) { concList.Add(line); } } } // 如果你最后还是需要数组,直接转就行 string[] concArray = concList.ToArray();
这样处理之后,不仅能避免空引用异常,还能让代码更健壮~
内容的提问来源于stack exchange,提问作者rcarcia02
相关产品推荐
相关产品推荐

