什么是数组在C#中的魔法 [英] What's the magic of arrays in C#

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

问题描述

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

类型两者的 A B 从抽象继承的System.Array ,但在没有真正的类内置库(似乎有一些运行时类型,你找不到的类型认定中的类的 INT [] )。你能告诉我在编译时会发生什么?而为什么他们(C#团队)让这个设计(我的意思是,为什么它不是像阵列< T> ,而不是他们使用的是带编译魔法抽象类)?

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编译器,然后翻译成这台机器code:

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运code的的 newarr 的,而不是创建一个类的实例通常的 newobj 的运算code。而简单的翻译,以实际获取创建的对象的CLR辅助函数。您可以在与SSCLI20源$ C ​​$ C这个辅助函数一看,看, CLR \\ SRC \\虚拟机\\ jithelpers.cpp 。过大张贴在这里,但它在很大程度上优化,以使这种code运行速度有可能的,不必提供给CLR code类型内部的直接访问。

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天全站免登陆