如果你想使用类似StringBuilder的,因为它是清洁剂绕过而努力,那么你可以使用像我创建了下面的StringBuilder替代。
它所做的最重要的不同之处在于,它允许访问内部数据,而无需首先将其组装成字符串或ByteArray。这意味着您不必将内存需求加倍,并且可能会尝试分配适合您整个对象的连续内存块。
注意:我相信在内部使用List<string>()
有更好的选择,但这很简单,并且证明对我的目的来说足够好。
public class StringBuilderEx
{
List<string> data = new List<string>();
public void Append(string input)
{
data.Add(input);
}
public void AppendLine(string input)
{
data.Add(input + "\n");
}
public void AppendLine()
{
data.Add("\n");
}
/// <summary>
/// Copies all data to a String.
/// Warning: Will fail with an OutOfMemoryException if the data is too
/// large to fit into a single contiguous string.
/// </summary>
public override string ToString()
{
return String.Join("", data);
}
/// <summary>
/// Process Each section of the data in place. This avoids the
/// memory pressure of exporting everything to another contiguous
/// block of memory before processing.
/// </summary>
public void ForEach(Action<string> processData)
{
foreach (string item in data)
processData(item);
}
}
现在您可以使用以下代码将整个内容转储到文件。
var stringData = new StringBuilderEx();
stringData.Append("Add lots of data");
using (StreamWriter file = new System.IO.StreamWriter(localFilename))
{
stringData.ForEach((data) =>
{
file.Write(data);
});
}
这是不可行的,如果他需要使用字符串的东西之前,写它虽然。 – Skurmedel 2010-02-10 11:43:54
绝对是真的,但他当然没有说这是一个要求,所以我没有做出任何假设。 – 2010-02-10 11:46:55