考虑以下几点:
长尺寸= int.MaxValue;
长[] =巨大的新长【尺寸】; //抛出OutOfMemoryException异常
长[] =巨大的新长[尺寸+ 1]; //抛出发生OverflowException
我知道有一个单独的对象,这也解释了第一个异常的大小2GB限制,但为什么我得到一个不同的异常,一旦元素的个数超过32位?
(我使用的是64位的计算机如果这很重要)。
编辑:我还可以定义和使用,接受长
,没有任何问题索引器:
内部密封类MyClass的
{
公共对象本[长×]
{
得到
{
Console.WriteLine({0},X);
返回null;
}
}
}
...
长尺寸= int.MaxValue;
MyClass的航空自卫队=新MyClass的();
对象o =航空自卫队[尺寸* 50]。 //输出107374182350
解决方案
所以,从我收集的,像下面是发生在这里:
在一般索引器可以使用任何类型的参数。 内置的数组索引可以接受任何整型... 但是内置数组索引需要一个值,该值&LT的底层实现; = Int32.MaxValue
,将抛出溢出例外的值超出 Int32.MaxValue
。
在后一点感觉像某种怪异的矛盾(接受类型比的Int32
大,但如果你碰巧实际使用任何这些额外的比特抛出一个异常) ,这是显然的事实,一些本是成功的一半,实现了其将被允许拥有超过 Int32.MaxValue
元素阵列的未来执行的副作用
Consider the following:
long size = int.MaxValue;
long[] huge = new long[size]; // throws OutOfMemoryException
long[] huge = new long[size + 1]; // throws OverflowException
I know there is a 2GB limit on the size of a single object, which explains the first exception, but why do I get a different exception once the number of elements surpasses 32bits?
(I am using a 64-bit computer if that's important).
EDIT: I can also define and use an indexer that accepts a long
with no problems:
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
解决方案
So from what I've gathered, something like the following is happening here:
Indexers in general could use any type of parameter. The built-in array indexers can accept any integral type... But the underlying implementation of the built-in array indexers requires a value that is<= Int32.MaxValue
and will throw an overflow exception for a value that exceeds Int32.MaxValue
.
While the latter point feels like some kind of weird contradiction (accepting types larger than Int32
, but throwing an exception if you happen to actually use any of those extra bits), it is apparently a side-effect of the fact that some of this is half-implemented for the future implementation of arrays which will be allowed to have more than Int32.MaxValue
elements.