gpt4 book ai didi

c# - 分配大数组; OutOfMemoryException VS 溢出异常

转载 作者:太空狗 更新时间:2023-10-29 21:13:48 25 4
gpt4 key购买 nike

考虑以下几点:

long size = int.MaxValue;
long[] huge = new long[size]; // throws OutOfMemoryException
long[] huge = new long[size + 1]; // throws OverflowException

我知道单个对象的大小有 2GB 的限制,这解释了第一个异常,但为什么一旦元素数量超过 32 位,我就会得到不同的异常?

(如果这很重要,我使用的是 64 位计算机)。

编辑:我还可以定义和使用一个索引器,它可以毫无问题地接受 long:

internal sealed class MyClass
{
public object this[long x]
{
get
{
Console.WriteLine("{0}", x);
return null;
}
}
}

...

long size = int.MaxValue;
MyClass asdf = new MyClass();
object o = asdf[size * 50]; // outputs 107374182350

最佳答案

C# 数组由 System.Int32 索引。由于 size + 1 超出了 Int32.MaxValue,您会遇到整数溢出。

如果您真的想使用 long 作为索引,请使用需要 long 的 Array.CreateInstance 重载。

关于c# - 分配大数组; OutOfMemoryException VS 溢出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10946513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com