C#中数组的神奇之处是什么 [英] What's the magic of arrays in C#

查看:33
本文介绍了C#中数组的神奇之处是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int[] a = new int[5];
string[] b = new string[1];

ab 的类型都继承自抽象的System.Array,但是内置的没有真正的类库(好像有一些运行时类型,你找不到int[]的类型定义类).你能告诉我编译时会发生什么吗?以及为什么他们(c# 团队)做出这种设计(我的意思是为什么它不像 Array,而是使用具有编译器魔法的抽象类)?

The types of both a and b inherit from the abstract System.Array, but there is no real classes in the built-in library(it seems that there are some runtime types, you can't find the type defination class of an int[]). Can you tell me what happens while compiling? And why did they(the c# team) make this design(I mean why it's not something like Array<T>,instead they are using an abstract class with compiler magics)?

推荐答案

试图在 .NET 类型系统中解决这个问题并不会让你走得很远.JIT 编译器和 CLR 中内置了核心支持来处理创建数组.像这样的声明:

Trying to reason this out within the .NET type system doesn't get you very far. There is core support built into the JIT compiler and the CLR to deal with creating arrays. A statement like this:

        var arr = new int[5];

生成此 IL:

  IL_0001:  ldc.i4.5
  IL_0002:  newarr     [mscorlib]System.Int32

然后 JIT 编译器将其翻译成此机器代码:

Which the JIT compiler then translate into this machine code:

00000035  mov         edx,5                 ; arg2 = array size
0000003a  mov         ecx,6F535F06h         ; arg1 = typeof(int)
0000003f  call        FFD52128              ; call JIT_NewArr1(type, size)

这里的核心成分是专用的 IL 操作码 newarr,而不是创建类实例的常见 newobj 操作码.以及对实际创建对象的 CLR 辅助函数的简单转换.您可以使用 SSCLI20 源代码 clr\src\vm\jithelpers.cpp 查看此辅助函数.太大了,无法在此处发布,但它经过大量优化以使此类代码尽可能快地运行,可以直接访问 CLR 代码可用的内部类型.

Core ingredients here are the dedicated IL opcode, newarr, instead of the usual newobj opcode that creates an instance of a class. And the simple translation to a CLR helper function that actually gets the object created. You can have a look-see at this helper function with the SSCLI20 source code, clr\src\vm\jithelpers.cpp. Too large to post here, but it is heavily optimized to make this kind of code run as fast possible, having direct access to the type internals available to CLR code.

有两个可用的帮助器,JIT_NewArr1() 创建一维(向量)数组,JIT_NewMDArr() 创建多维数组.与可用于 Type.MakeArrayType() 的两个重载进行比较.

There are two of these helpers available, JIT_NewArr1() creates one-dimensional (vector) arrays and JIT_NewMDArr() creates multi-dimensional arrays. Compare to the two overloads available for Type.MakeArrayType().

这篇关于C#中数组的神奇之处是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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