请帮助我理解这段代码有什么问题。 (我正在尝试构建一个字符串,从文本文件中逐行获取部分字符串。)
我收到运行时错误 “在对象引用的实例中未设置为对象” 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);
答案 0 :(得分:10)
看看以下几行:
StringBuilder strbuild = new StringBuilder();
strbuild = null;
当您致电strbuild.Append(...)
时,您期待会发生什么?为什么要将strbuild
设置为空?
你似乎喜欢两行变量初始化 - 这是另一个例子:
string str = null;
str = reader.ReadLine().ToString();
这更容易阅读:
string str = reader.ReadLine();
(ReadLine
已经返回一个字符串,因此您无需在结果上调用ToString()
。)
但是,我做建议您对using
使用StreamReader
语句 - 否则当抛出异常时,您将打开阅读器。< / p>
关于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());
答案 1 :(得分:6)
初始化后,您将stringbuilder设置为null。
更改
StringBuilder strbuild = new StringBuilder();
strbuild = null;
到
StringBuilder strbuild = new StringBuilder();
忽略该行
strbuild = null;
答案 2 :(得分:2)
更改
StringBuilder strbuild = new StringBuilder();
strbuild = null;
到
StringBuilder strbuild = null;
strbuild = new StringBuilder();
或者,为了防止这种错误:
StringBuilder strbuild = new StringBuilder();
答案 3 :(得分:1)
您的示例中有一些错误,这是第一个更正的版本:
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());