StringBuilder 实例中的运行时错误
请帮助我理解这段代码有什么问题。 (我正在尝试构建一个字符串,从文本文件中逐行获取其中的一部分)。
我在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看一下这些行:
当您调用
strbuild.Append(...)
时,您期望会发生什么?为什么要将strbuild
设置为 null?您似乎喜欢两行变量初始化 - 这是另一个示例:
这将更容易阅读,因为:
(
ReadLine
已经返回一个字符串,因此您不需要调用ToString()
结果。)但是,我确实建议您对
StreamReader
使用using
语句 - 否则当抛出异常,您将使读者保持开放状态。TextReader.ReadLine()
的一个好处是,完成后它会返回 null。您不需要先查看然后再阅读。最后,如果您只测试单个字符,则不需要子字符串 - 只需使用字符串索引器来获取字符。所以,你可以:
Look at these lines:
What do you expect to happen when you then call
strbuild.Append(...)
? Why are you settingstrbuild
to null at all?You seem to be fond of two-line variable initialization - here's another example:
This would be more easily readable as just:
(
ReadLine
already returns a string, so you don't need to callToString()
on the result.)However, I do suggest that you use a
using
statement for theStreamReader
- 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 设置为 null。
更改
为
省略该行
You are setting the stringbuilder to null after initialization.
Change
to
leaving out the line
改为
or
,可以防止此类错误:
Change
to
or, to prevent this kind of error:
您的示例中有很多错误,这是第一个更正的版本:
There are some many errors within your example, here is a first corrected version: