C# - How do generics with the new() constraint get

2019-06-22 07:09发布

问题:

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


标签: c# generics clr