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

本文关键字:运行时错误 StringBuilder 字符串 插入 | 更新日期: 2023-09-27 18:11:47

我试图将字符串插入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);
        }
    }
}

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

此行返回整个StringBuilder内容:

return this._value.ToString();

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

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

并将其附加在此处:

this._value.Append(value);

你的StringBuilder会很快变得巨大,因为每次你调用"setter"时,你都会再次将整个内容的副本放入其中。


相反,您可能会考虑通过您的属性暴露StringBuilder

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

然后像这样使用:

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

试试上面的

我还发现了这个解释为什么StringBuilder:没有+=

为什么没有';微软是否重载了字符串生成器的+=运算符?