这是我的代码行:
StringBuilder myCompleteMessage = new StringBuilder();
myCompleteMessage.Capacity = Int32.MaxValue-1;
也试过:
myCompleteMessage.Capacity = myCompleteMessage.MaxCapacity-1;
我在第 2 行遇到异常。
Exception of type 'System.OutOfMemoryException' was thrown.
堆栈跟踪:
at System.String.GetStringForStringBuilder(String value, Int32 startIndex, Int32 length, Int32 capacity)
at System.Text.StringBuilder.set_Capacity(Int32 value)
at Orca.Server.HandleClientComm(Object newClient) in C:\Users\Dan\Documents\Visual Studio 2010\Projects\msig\Orca\Server.cs:line 100
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart(Object obj)
最佳答案
假设您在 32 位系统上,第二行总是会失败。您要求 .NET 为您的 StringBuilder 分配 4 GB 的空间,这比进程必须使用的内存多(感谢 Joel 指出 char 占用 2 个字节,而不是 1 个字节)。
编辑
如果您使用 ILSpy 查看 StringBuilder
,您会在 Capacity
的集合中看到这段代码:
if (this.Capacity != value)
{
int num = value - this.m_ChunkOffset;
char[] array = new char[num];
Array.Copy(this.m_ChunkChars, array, this.m_ChunkLength);
this.m_ChunkChars = array;
}
通过将 Capacity 设置为 int.MaxValue - 1,您告诉 .NET 尝试分配一个 4 GB 的字符数组,这就是代码失败的原因。
关于c# - 更改容量时出现 StringBuilder 异常!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6619182/