C# 为什么分配一个int.MaxValue数组失败,而分配两个int.MaxValue/2大小的数组失败?

C# 为什么分配一个int.MaxValue数组失败,而分配两个int.MaxValue/2大小的数组失败?,c#,C#,为什么分配大小为int.MaxValue的字节数组失败 byte[] array1 = new byte[int.MaxValue]; // throws an OutOfMemoryException 而大小为int.MaxValue/2的两个数组的分配不正确吗 byte[] array2 = new byte[int.MaxValue / 2]; byte[] array3 = new byte[int.MaxValue / 2]; .NET中对象的最大大小为2

为什么分配大小为
int.MaxValue
的字节数组失败

    byte[] array1 = new byte[int.MaxValue]; // throws an OutOfMemoryException 
而大小为
int.MaxValue/2
的两个数组的分配不正确吗

    byte[] array2 = new byte[int.MaxValue / 2];
    byte[] array3 = new byte[int.MaxValue / 2];

.NET中对象的最大大小为2GB:


int.MaxValue+数组开销略大于2 GB

我不知道c#中int.MaxValue的值,但我认为.Net不允许大于2GB的对象

在.Net的最新版本中(至少从4.5开始),您可以分配大于2GB的对象-但是您必须设置gcAllowVeryLargeObjects-

(2GB=2*1024^3)>(2147483647=MaxValue);int.MaxValue-50的分配也失败,这是真的。2GB正好比int多1。MaxValueArray除了其主数据存储之外还保存一些附加信息(一些来自
对象
,一些特定于数组),这就是为什么您提前到达边界的原因。