【问题标题】:Inserting String Into StringBuilder Causes Runtime Error将字符串插入 StringBuilder 会导致运行时错误
【发布时间】: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


【解决方案1】:

此行返回整个 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 字符串和行)?
  • @JakeM 您可以随时重新定义“+”运算符。这将允许你做你想做的事。以下是如何进行的示例:msdn.microsoft.com/en-us/library/6fbs5e2h.aspx。但是,我确实建议您使用 AppendLine 方法,因为它的含义并不模棱两可,而且再清楚不过了。
【解决方案2】:
StringBuilder sb = new StringBuilder();
foreach (string line in fileContents) 
{
    if (isKeyValuePair(line))
       sb.AppendLine(line); // Exception of type 'System.OutOfMemoryException' was thrown.
}

试试上面的

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

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

【讨论】:

    猜你喜欢
    • 2022-11-16
    • 2012-06-24
    • 1970-01-01
    • 1970-01-01
    • 2016-05-09
    • 2017-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多