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

纵然是瞬间 提交于 2019-12-10 13:57:33

问题


public T Foo<T, U>(U thing) where T : new()
{
    return new T();
}

When there is no new() constraint, I understand how it would work. The JIT Compiler sees T and if it's a reference type makes uses the object versions of the code, and specializes for each value type case.

How does it work if you have a new T() in there? Where does it look for?


回答1:


If you mean, what does the IL look like, the compiler will compile in a call to Activator.CreateInstance<T>.

The type you pass as T must have a public parameterless constructor to satisfy the compiler.

You can test this in Try Roslyn:

public static T Test<T>() where T : class, new()
{
    return new T();
}

becomes:

.method public hidebysig static 
    !!T Test<class .ctor T> () cil managed 
{
    // Method begins at RVA 0x2050
    // Code size 6 (0x6)
    .maxstack 8

    IL_0000: call !!0 [mscorlib]System.Activator::CreateInstance<!!T>()
    IL_0005: ret
} // end of method C::Test


来源:https://stackoverflow.com/questions/32553449/c-sharp-how-do-generics-with-the-new-constraint-get-machine-code-generated

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