为什么"UInt64 [] arr = new UInt64 [UInt64.MaxValue];" 扔异常?

Tec*_*hee 1 c#

为什么以下代码抛出异常"算术运算导致溢出".

UInt64[] arr=new UInt64[UInt64.MaxValue];
Run Code Online (Sandbox Code Playgroud)

ken*_*ytm 7

我猜是因为8 * UInt64.MaxValue要求分配完全字节,这个乘法显然会溢出64位寄存器.


Nic*_*sen 7

因为索引器只接受Int32值.你可以做

UInt64[] arr=new UInt64[Int32.MaxValue];
Run Code Online (Sandbox Code Playgroud)

但这就是极限.

编辑:从技术上讲,您可以使用理论上高于Int32.MaxValue的值结构索引数组(因为您可以使用long或uint索引数组),但是,当值超过时,您将遇到运行时错误Int32.MaxValue.