.NET数组的最大大小 [英] Maximum size of .NET arrays

查看:159
本文介绍了.NET数组的最大大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这并不是说我会永远需要做到这一点,但我想了解它是如何工作/无法正常工作。我GOOGLE了相当多的数组的最大长度,并不能真正发现任何东西。

Not that I would ever need to do this, but I want to understand how it works/doesn't work. I googled quite a bit for the maximum length of an array and can't really find anything.

long[] hugeArray = new long[long.MaxValue];

//No exceptions
Console.WriteLine("Init");

//Overflow exception
Console.WriteLine(hugeArray.LongLength.ToString());

hugeArray = new long[int.MaxValue];

//OutOfMemoryException
Console.WriteLine( hugeArray.Length.ToString());

和我想跟进的问题是,如果有一个限制,我初始化之外的限制,为什么没有异常时,只有在使用创建?而这事编译器应该抓住?

And I guess a follow up question would be, if there is a limit and I am initializing outside that limit, why no exception when creating only when using? And is this something the compiler should catch?

推荐答案

据的 SpankyJ ,.NET 2.0至少有每个阵列2 GB的限制。 8个字节(sizeof的长)*〜2 ^ 31 = 16千兆字节(更不用说实际所需的内存)。至于溢出,我同意marcc这可能是因为数组预计将INT-索引(如见的这个方法虽然我有点不确定对此,作为的此重载利用了Int64的长度数组。这可能是一个只能在以后的版本中可用的扩展。

According to SpankyJ, .NET 2.0 at least had a limit of 2 GB per array. 8 bytes (sizeof long) * ~2^31 = 16 gigabytes (not to mention the actual memory required). As for the Overflow, I agree with marcc that is probably because arrays are expected to be int-indexed (see e.g. this method Though I'm a bit uncertain regarding this, as this overload takes an array of Int64 lengths. This may be an extension only available in later versions.

不过,总的来说,这主要是一个理论问题。其实任何人都靠这可能是做错了什么。

Overall, though, this is mostly a theoretical issue. Anyone actually relying on this is likely doing something wrong.

这篇关于.NET数组的最大大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆