C# 中数组索引的类型是什么?
例如,在下面的代码中,是否会在访问数组元素(第三行)之前将索引转换为 int?
T[] myArray = new T[255];
byte index = 2;
T element = myArray[index];
如果不是,使用类型为“byte”的索引访问数组元素是否比使用类型为“int”的索引更快?
谢谢
最佳答案
原答案:
是的,它总是一个 int
对于数组访问表达式。其他索引器(例如在 Dictionary<,>
中)可以有其他参数类型,但数组访问索引始终是 int
,必要时通过促销(根据您的示例)。
但是等等!
实际上,查看 C# 5 规范的第 7.6.6.1 节,我不太确定:
For an array access, the primary-no-array-creation-expression of the element-access must be a value of an array-type. Furthermore, the argument-list of an array access is not allowed to contain named arguments.The number of expressions in the argument-list must be the same as the rank of the array-type, and each expression must be of type
int
,uint
,long
,ulong
, or must be implicitly convertible to one or more of these types. The result of evaluating an array access is a variable of the element type of the array, namely the array element selected by the value(s) of the expression(s) in the argument-list.The run-time processing of an array access of the form P[A], where P is a primary-no-array-creation-expression of an array-type and A is an argument-list, consists of the following steps:
P
is evaluated. If this evaluation causes an exception, no further steps are executed.The index expressions of the argument-list are evaluated in order, from left to right. Following evaluation of each index expression, an implicit conversion (§6.1) to one of the following types is performed:
int
,uint
,long
,ulong
. The first type in this list for which an implicit conversion exists is chosen. For instance, if the index expression is of typeshort
then an implicit conversion toint
is performed, since implicit conversions fromshort
toint
and fromshort
tolong
are possible. If evaluation of an index expression or the subsequent implicit conversion causes an exception, then no further index expressions are evaluated and no further steps are executed.
确实这段代码有效:
string[] array = new string[10];
long index = 10;
string element = array[index];
因此,在您的特定情况下 byte
将被提升为 int
,访问索引访问并不总是通过 int
.
即使在 .NET 4.5 中支持“大型数组”,我认为您也不能创建超过 int.MaxValue
的数组。元素,但我可能是错的。 (恐怕我现在没有时间测试它。)
关于c# - C#中数组索引的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16486533/