为什么英寸长"被允许在C#数组的长度? [英] Why is "long" being allowed as array length in C#?

查看:164
本文介绍了为什么英寸长"被允许在C#数组的长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想尝试分配4十亿字节数组,这是我的C#code:

I wanted to try to allocate a 4 billion bytes array and this is my C# code:

long size = 4 * 1000;
size *= 1000;
size *= 1000;
byte[] array = new byte[size];

这code失败,出现System.OverflowException 对包含该行。好吧,原来长度返回 INT ,所以数组长度也被限制到什么 INT 可以存储。

this code fails with System.OverflowException on the line containing new. Okay, turns out Length returns int, so the array length is also limited to what int can store.

那么为什么没有编译时错误和被允许作为数组元素的配置是多少?

Then why is there no compile-time error and long is allowed to be used as the number of array elements at allocation?

推荐答案

由于该规范是这么说的第7.6.10.4:

Because the specification says so in section 7.6.10.4:

每个EX pression在EX pression列表的类型必须为 INT UINT ULONG ,或隐式转换为上述类型之一以上。

Each expression in the expression list must be of type int, uint, long, or ulong, or implicitly convertible to one or more of these types.

这是最有可能很容易的允许的创作阵列比2吉布大的,即使他们不支持的的(但会没有的语言的变化,一旦CLR使得这样的变化)。 单不支持这一点,但是和的。NET 4.5显然将允许更大的阵列也

This is most likely to easily allow creation of arrays larger than 2 GiB, even though they are not supported yet (but will be without a language change once the CLR makes such a change). Mono does support this, however and .NET 4.5 apparently will allow larger arrays too.

对于数组长度作为一个 INT 顺便说一句:还有 LongLength ,返回。这是在.NET 1.1和可能是一个面向未来的变化。

Regarding array length being an int by the way: There is also LongLength, returning a long. This was in .NET 1.1 and probably a future-proofing change.

这篇关于为什么英寸长"被允许在C#数组的长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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