C# 数组索引器
C# Array Indexer
我想知道:C#数组索引器是如何实现的?
您可以使用从 ulong
到 sbyte
的基本上每个整数值对 C# 数组进行索引,内部实现是否每次都简单地转换为通用类型?
要明确这一点:
ulong i = 10;
var o = myArray[i];
被翻译成类似的东西:
ulong i =10;
var o = myArray[(int /*or whatver is the default type used*/)i];
?
数组索引器的类型是整数,所以是的,该值将被转换为整数。您可以通过检查 IL
代码来验证这一点。给出这个例子:
var myArray = new[]{ 1,2,3 };
ulong i = 10;
var o = myArray[i];
这将编译成:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 29 (0x1d)
.maxstack 3
.locals init ([0] int32[] myArray,
[1] uint64 i,
[2] int32 o)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr [mscorlib]System.Int32
IL_0007: dup
IL_0008: ldtoken field valuetype '<PrivateImplementationDetails>'/'__StaticArrayInitTypeSize=12' '<PrivateImplementationDetails>'::E429CCA3F703A39CC5954A6572FEC9086135B34E
IL_000d: call void [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array,
valuetype [mscorlib]System.RuntimeFieldHandle)
IL_0012: stloc.0
IL_0013: ldc.i4.s 10
IL_0015: conv.i8
IL_0016: stloc.1
IL_0017: ldloc.0
IL_0018: ldloc.1
IL_0019: conv.ovf.i.un
IL_001a: ldelem.i4
IL_001b: stloc.2
IL_001c: ret
} // end of method Program::Main
转换发生在 IL_0019
,使用 conv.ovf.i.un
指令。
Converts the unsigned value on top of the evaluation stack to signed native int, throwing OverflowException on overflow.
我想知道:C#数组索引器是如何实现的?
您可以使用从 ulong
到 sbyte
的基本上每个整数值对 C# 数组进行索引,内部实现是否每次都简单地转换为通用类型?
要明确这一点:
ulong i = 10;
var o = myArray[i];
被翻译成类似的东西:
ulong i =10;
var o = myArray[(int /*or whatver is the default type used*/)i];
?
数组索引器的类型是整数,所以是的,该值将被转换为整数。您可以通过检查 IL
代码来验证这一点。给出这个例子:
var myArray = new[]{ 1,2,3 };
ulong i = 10;
var o = myArray[i];
这将编译成:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 29 (0x1d)
.maxstack 3
.locals init ([0] int32[] myArray,
[1] uint64 i,
[2] int32 o)
IL_0000: nop
IL_0001: ldc.i4.3
IL_0002: newarr [mscorlib]System.Int32
IL_0007: dup
IL_0008: ldtoken field valuetype '<PrivateImplementationDetails>'/'__StaticArrayInitTypeSize=12' '<PrivateImplementationDetails>'::E429CCA3F703A39CC5954A6572FEC9086135B34E
IL_000d: call void [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array,
valuetype [mscorlib]System.RuntimeFieldHandle)
IL_0012: stloc.0
IL_0013: ldc.i4.s 10
IL_0015: conv.i8
IL_0016: stloc.1
IL_0017: ldloc.0
IL_0018: ldloc.1
IL_0019: conv.ovf.i.un
IL_001a: ldelem.i4
IL_001b: stloc.2
IL_001c: ret
} // end of method Program::Main
转换发生在 IL_0019
,使用 conv.ovf.i.un
指令。
Converts the unsigned value on top of the evaluation stack to signed native int, throwing OverflowException on overflow.