StringBuilder 实例中的运行时错误

发布于 2024-08-23 07:14:59 字数 864 浏览 3 评论 0原文

请帮助我理解这段代码有什么问题。 (我正在尝试构建一个字符串,从文本文件中逐行获取其中的一部分)。

我在 strbuild.Append(str); 行上收到运行时错误“在对象引用的实例中未设置为对象”

        StreamReader reader = new StreamReader("buf.txt", System.Text.Encoding.ASCII);
        StringBuilder strbuild = new StringBuilder();
        strbuild = null;

        while (reader.Peek() >= 0)
        {
            string str = null;
            str = reader.ReadLine().ToString();

            string segment = str.Substring(0, 1);

            if (segment == "A")
            {
                strbuild.Append(str); //here  i get an error
            }
            else if (segment == "B")
            {
                strbuild.Append("BET");
            }

        }
        printstr = strbuild.ToString();
        reader.Close();

        MessageBox.Show(printstr);

Please, help me understand, what's wrong with this code. (I am trying to build a string, taking parts of it line by line from a text file).

I get a runtime error "In the instance of the object reference not set to an object" on the line strbuild.Append(str);

        StreamReader reader = new StreamReader("buf.txt", System.Text.Encoding.ASCII);
        StringBuilder strbuild = new StringBuilder();
        strbuild = null;

        while (reader.Peek() >= 0)
        {
            string str = null;
            str = reader.ReadLine().ToString();

            string segment = str.Substring(0, 1);

            if (segment == "A")
            {
                strbuild.Append(str); //here  i get an error
            }
            else if (segment == "B")
            {
                strbuild.Append("BET");
            }

        }
        printstr = strbuild.ToString();
        reader.Close();

        MessageBox.Show(printstr);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

凉城凉梦凉人心 2024-08-30 07:14:59

看一下这些行:

StringBuilder strbuild = new StringBuilder();
strbuild = null;

当您调用 strbuild.Append(...) 时,您期望会发生什么?为什么要将 strbuild 设置为 null?

您似乎喜欢两行变量初始化 - 这是另一个示例:

string str = null;
str = reader.ReadLine().ToString();

这将更容易阅读,因为:

string str = reader.ReadLine();

(ReadLine 已经返回一个字符串,因此您不需要调用 ToString() 结果。)

但是,我确实建议您对 StreamReader 使用 using 语句 - 否则当抛出异常,您将使读者保持开放状态。

TextReader.ReadLine() 的一个好处是,完成后它会返回 null。您不需要先查看然后再阅读。

最后,如果您只测试单个字符,则不需要子字符串 - 只需使用字符串索引器来获取字符。所以,你可以:

StringBuilder builder = new StringBuilder();

// Consider using File.OpenText
using (StreamReader reader = new StreamReader("buf.txt", Encoding.ASCII))
{
    string line;
    // Normally side-effect + test is ugly, but this is a common and
    // neat idiom
    while ((line = reader.ReadLine()) != null)
    {
        // TODO: What do you want to happen for empty lines?
        char segment = str[0];
        if (segment == 'A')
        {
            builder.Append(line);
        }
        else if (segment == 'B')
        {
            builder.Append("BET");
        }
    }
}
MessageBox.Show(builder.ToString());

Look at these lines:

StringBuilder strbuild = new StringBuilder();
strbuild = null;

What do you expect to happen when you then call strbuild.Append(...)? Why are you setting strbuild to null at all?

You seem to be fond of two-line variable initialization - here's another example:

string str = null;
str = reader.ReadLine().ToString();

This would be more easily readable as just:

string str = reader.ReadLine();

(ReadLine already returns a string, so you don't need to call ToString() on the result.)

However, I do suggest that you use a using statement for the StreamReader - otherwise when an exception is thrown, you'll be leaving the reader open.

One nice thing about TextReader.ReadLine() is that it returns null when you're done. You don't need to peek and then read.

Finally, if you're only testing a single character you don't need a substring - just use the string indexer to get a char. So, you could have:

StringBuilder builder = new StringBuilder();

// Consider using File.OpenText
using (StreamReader reader = new StreamReader("buf.txt", Encoding.ASCII))
{
    string line;
    // Normally side-effect + test is ugly, but this is a common and
    // neat idiom
    while ((line = reader.ReadLine()) != null)
    {
        // TODO: What do you want to happen for empty lines?
        char segment = str[0];
        if (segment == 'A')
        {
            builder.Append(line);
        }
        else if (segment == 'B')
        {
            builder.Append("BET");
        }
    }
}
MessageBox.Show(builder.ToString());
囚我心虐我身 2024-08-30 07:14:59

您在初始化后将 stringbuilder 设置为 null。

更改

StringBuilder strbuild = new StringBuilder(); 
strbuild = null; 

StringBuilder strbuild = new StringBuilder(); 

省略该行

strbuild = null;

You are setting the stringbuilder to null after initialization.

Change

StringBuilder strbuild = new StringBuilder(); 
strbuild = null; 

to

StringBuilder strbuild = new StringBuilder(); 

leaving out the line

strbuild = null;
少钕鈤記 2024-08-30 07:14:59

改为

  StringBuilder strbuild = new StringBuilder();
  strbuild = null;

or

  StringBuilder strbuild = null;
  strbuild = new StringBuilder();

,可以防止此类错误:

  StringBuilder strbuild = new StringBuilder();

Change

  StringBuilder strbuild = new StringBuilder();
  strbuild = null;

to

  StringBuilder strbuild = null;
  strbuild = new StringBuilder();

or, to prevent this kind of error:

  StringBuilder strbuild = new StringBuilder();
小嗷兮 2024-08-30 07:14:59

您的示例中有很多错误,这是第一个更正的版本:

StringBuilder strbuild = new StringBuilder();

// Put resource into using statements, for deterministic cleanup
using (TextReader reader = new StreamReader("buf.txt", System.Text.Encoding.ASCII))
{
    string line;

    //Maybe looks a little ugly the first time, but is commonly used to
    //process all the lines of a file (.ReadToEnd() can cause memory problems
    //on really big files)
    while ((line = reader.ReadLine()) != null)
    {
        //Instead of if, else if, else if, etc just take a switch
        //statement. Makes it much easier to read.
        switch (line[0])
        {
            //If you need case insensitivity put both versions of the character
            //before your first line of code
            case 'A':
            case 'a':
                strbuild.Append(line);
                break;
            //Otherwise just use the lower or upper case version you like
            case 'B':
                strbuild.Append("BET");
                break;
        }
    }
}

//Put the result of the StringBuilder directly into the Show() function
MessageBox.Show(strbuild.ToString());

There are some many errors within your example, here is a first corrected version:

StringBuilder strbuild = new StringBuilder();

// Put resource into using statements, for deterministic cleanup
using (TextReader reader = new StreamReader("buf.txt", System.Text.Encoding.ASCII))
{
    string line;

    //Maybe looks a little ugly the first time, but is commonly used to
    //process all the lines of a file (.ReadToEnd() can cause memory problems
    //on really big files)
    while ((line = reader.ReadLine()) != null)
    {
        //Instead of if, else if, else if, etc just take a switch
        //statement. Makes it much easier to read.
        switch (line[0])
        {
            //If you need case insensitivity put both versions of the character
            //before your first line of code
            case 'A':
            case 'a':
                strbuild.Append(line);
                break;
            //Otherwise just use the lower or upper case version you like
            case 'B':
                strbuild.Append("BET");
                break;
        }
    }
}

//Put the result of the StringBuilder directly into the Show() function
MessageBox.Show(strbuild.ToString());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文