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

时间:2014-07-08 03:15:50

标签: 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.
}

分支机构的实施

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);
        }
    }
}

2 个答案:

答案 0 :(得分:5)

此行返回整个 StringBuilder内容:

return this._value.ToString();

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

curBranch.Value += line + "\r\n";

并将其附加到此处:

this._value.Append(value);

你的StringBuilder会很快变大,因为每次你打电话给#34; setter&#34;您将整个内容的副本再次放入其中。


您可能会考虑通过您的财产公开StringBuilder

public StringBuilder Value
{
    get { return this._value; }   
}

然后就这样使用它:

curBranch.Value.AppendLine(line);

答案 1 :(得分:2)

StringBuilder sb = new StringBuilder();
foreach (string line in fileContents) 
{
    if (isKeyValuePair(line))
       sb.AppendLine(line); // Exception of type 'System.OutOfMemoryException' was thrown.
}

试试上面的

我也找到了这个解释为什么+ =不是#39;对于StringBuilder:

Why didn't microsoft overload the += operator for stringbuilder?