将字符串插入StringBuilder会导致运行时错误

saz*_*azr 0 c# stringbuilder string-concatenation

我试图插入一个字符串,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.
}
Run Code Online (Sandbox Code Playgroud)

执行分支

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Gra*_*ICA 5

该行返回整个 StringBuilder内容:

return this._value.ToString();
Run Code Online (Sandbox Code Playgroud)

然后在前一个内容的末尾添加一个字符串:

curBranch.Value += line + "\r\n";
Run Code Online (Sandbox Code Playgroud)

并将其附加到此处:

this._value.Append(value);
Run Code Online (Sandbox Code Playgroud)

StringBuilder很快就会变得非常庞大,因为每当你打电话给"setter"时,你都会将整个内容的副本再次放入其中.


你可能会考虑的是StringBuilder通过你的财产暴露:

public StringBuilder Value
{
    get { return this._value; }   
}
Run Code Online (Sandbox Code Playgroud)

然后就像这样使用它:

curBranch.Value.AppendLine(line);
Run Code Online (Sandbox Code Playgroud)