发生OutOfMemoryException时?

3 c# memory-management

考虑以下代码:

string value = new string('a', int.MaxValue);
Run Code Online (Sandbox Code Playgroud)

当我们运行该代码时发生OutOfMemoryException.Windows 8中的物理内存限制为128 GB.

那么为什么.Net会抛出OutOfMemoryException那些代码呢?

此代码也从不抛出OutOfMemoryException:

List<string> list = new List<string>();
for (int i = 0; i < 100000000000; i++)
{
    list.Add(new string('a', 100 ));
}
Run Code Online (Sandbox Code Playgroud)

我在64位模式下运行它.

Pat*_*man 5

.NET中对象的最大大小为2 GB,即使gcAllowVeryLargeObjects在64位系统上启用也是如此(关于gcAllowVeryLargeObjects读取的文档字符串和其他非数组对象的最大大小不变.我想是因为它的实现方式) .

这意味着您只能分配大小为2GB的字符串.由于sizeof(char)是2并且您在类本身中有一点开销,因此您可以设置的最大大小int.MaxValue / 2 - 32.