如果你想使用類似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