首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >StreamReader NullReferenceException

StreamReader NullReferenceException
EN

Stack Overflow用户
提问于 2013-04-22 15:14:53
回答 3查看 5K关注 0票数 3

我正在创建一个函数,它将从一个StreamReader获取行数,不包括注释(以‘//’开头的行)和新行。

这是我的密码:

代码语言:javascript
复制
private int GetPatchCount(StreamReader reader)
    {
        int count = 0;

            while (reader.Peek() >= 0)
            {
                string line = reader.ReadLine();
                if (!String.IsNullOrEmpty(line))
                {
                    if ((line.Length > 1) && (!line.StartsWith("//")))
                    {
                        count++;
                    }
                }
            }

        return count;
    }

我的StreamReader的数据是:

代码语言:javascript
复制
// Test comment

但我得到了一个错误,“对象引用没有设置为对象的实例。”有办法纠正这个错误吗?

编辑发现,当的StreamReader为null时,就会发生这种情况。因此,关于musefan和Smith先生的建议代码,我想出了以下内容:

代码语言:javascript
复制
private int GetPatchCount(StreamReader reader, int CurrentVersion)
    {
        int count = 0;
            if (reader != null)
            {
            string line;
            while ((line = reader.ReadLine()) != null)
                if (!String.IsNullOrEmpty(line) && !line.StartsWith("//"))
                    count++;
            }
        return count;
    }

谢谢你的帮助!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-04-22 15:17:24

没有必要使用Peek(),这可能也是问题所在。你可以这么做:

代码语言:javascript
复制
string line = reader.ReadLine();
while (line != null)
{
    if (!String.IsNullOrEmpty(line) && !line.StartsWith("//"))
    {
        count++;
    }
    line = reader.ReadLine();
}

当然,如果您的StreamReader为null,那么您就有一个问题,但是仅用示例代码还不足以确定这一点--您需要调试它。应该有大量的调试信息供您计算出哪个对象实际上是空的。

票数 2
EN

Stack Overflow用户

发布于 2013-04-22 15:16:49

听起来你的reader对象是null

通过执行以下操作,可以检查读取器是否为空:

代码语言:javascript
复制
if (reader == null) {
   reader = new StreamReader("C:\\FilePath\\File.txt");
} 
票数 1
EN

Stack Overflow用户

发布于 2013-04-22 15:26:46

musefan建议的代码的更简洁的变体;只是一个ReadLine()代码。+1建议移除长度检查。

代码语言:javascript
复制
private int GetPatchCount(StreamReader reader)
{
    int count = 0;
    string line;
    while ((line = reader.ReadLine()) != null)
        if (!String.IsNullOrEmpty(line) && !line.StartsWith("//"))
            count++;
    return count;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16150606

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档