问题描述
我刚刚问过
考虑了一段时间之后,我想知道为什么C#
After thinking about this for a while, I'm wondering why the C# Compiler emitted IL like that.
为什么它不能说一些IL:调用T的默认构造函数?
Why couldn't it say some IL like: "Call T's default constructor"?
推荐答案
CIL中没有这样的说明()。
There is no such instruction in CIL (http://www.ecma-international.org/publications/standards/Ecma-335.htm).
假设我们可以添加一个,对此的另一种实现可能是在Type的VTable中,使默认构造函数在索引0处建立索引,然后JIT可以假定此信息并发出执行VTable查找,选择索引0并调用所定位函数的代码在此实体指向的地址VTable中的ry 0。
Assuming we can add one, an another implementation of this could be that in the Type's VTable we make the default constructor be indexed at index 0, and then the JIT can assume this information and emit code that does a VTable lookup, pick index 0 and call the function located at address pointed by this entry 0 in the VTable.
如您所见,这需要更改CLR数据结构,可能需要更改每个对象的布局,并可能需要针对值类型的不同解决方案( m忽略了这种情况,因为您专门说了class和new()。
As you can see this requires a change in CLR data structures, possibly each object's layout, and likely a different solution for value types (I'm ignoring that case, because you specifically say class and new().
这篇关于C#-为什么类new()约束使用Activator.CreateInstance< T>()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!