C# – new()约束的generics如何生成机器代码?
public T Foo(U thing) where T : new() { return new T(); }
当没有new()
约束时,我理解它是如何工作的。 JIT编译器看到T,如果它是引用类型,则使用代码的对象版本,并专门针对每个值类型的情况。
如果你有一个新的T(),它是如何工作的? 它在哪里寻找?
如果你的意思是,IL看起来是什么样的,编译器将在调用Activator.CreateInstance
编译。
作为T
传递的类型必须具有公共无参数构造函数以满足编译器。
你可以在Try Roslyn中测试一下 :
public static T Test() where T : class, new() { return new T(); }
变为:
.method public hidebysig static !!T Test () cil managed { // Method begins at RVA 0x2050 // Code size 6 (0x6) .maxstack 8 IL_0000: call !!0 [mscorlib]System.Activator::CreateInstance() IL_0005: ret } // end of method C::Test