加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 分配大型数组; OutOfMemoryException VS OverflowExceptio

发布时间:2020-12-15 04:10:41 所属栏目:百科 来源:网络整理
导读:考虑以下: long size = int.MaxValue;long[] huge = new long[size]; // throws OutOfMemoryExceptionlong[] huge = new long[size + 1]; // throws OverflowException 我知道单个对象的大小有2GB的限制,这解释了第一个异常,但是为什么一旦元素数量超过32位
考虑以下:
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索引.由于大小1超出Int32.MaxValue,因此会出现整数溢出.

如果你真的想使用long作为索引,那么使用需要很长的Array.CreateInstance的重载.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读