C# - Why does a class, new() constraint use Activator.CreateInstance<T>()? [duplicate]

只愿长相守 提交于 2019-12-10 17:12:11

问题


I just asked C# - How do generics with the new() constraint get machine code generated?

After thinking about this for a while, I'm wondering why the C# Compiler emitted IL like that.

Why couldn't it say some IL like: "Call T's default constructor"?


回答1:


There is no such instruction in CIL (http://www.ecma-international.org/publications/standards/Ecma-335.htm).

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.

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().



来源:https://stackoverflow.com/questions/32553686/c-sharp-why-does-a-class-new-constraint-use-activator-createinstancet

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!