【发布时间】:2014-07-08 03:15:50
【问题描述】:
我正在尝试将字符串插入到 StringBuilder 中,但出现运行时错误:
引发了“System.OutOfMemoryException”类型的异常。
为什么会发生这种情况,我该如何解决?
我的代码:
Branch curBranch("properties", "");
foreach (string line in fileContents)
{
if (isKeyValuePair(line))
curBranch.Value += line + "\r\n"; // Exception of type 'System.OutOfMemoryException' was thrown.
}
分支的实现
public class Branch {
private string key = null;
public StringBuilder _value = new StringBuilder(); // MUCH MORE EFFICIENT to append to. If you append to a string in C# you'll be waiting decades LITERALLY
private Dictionary <string, Branch> children = new Dictionary <string, Branch>();
public Branch(string nKey, string nValue) {
key = nKey;
_value.Append(nValue);
}
public string Key {
get { return key; }
}
public string Value {
get
{
return this._value.ToString();
}
set
{
this._value.Append(value);
}
}
}
【问题讨论】:
-
你基本上是在每次调用 curBranch.Value += line + "\r\n"; 时附加你在 stringbuilder 中的完整副本。我不认为这是在做你想做的事。
标签: c# stringbuilder string-concatenation