给出以下代码:
public class Test
{
public T Get1<T>()
{
return Activator.CreateInstance<T>();
}
public T Get2<T>() where T : new()
{
return new T();
}
}
两种方法都使用System.Activator
产生完全相同的方法主体,即:
.method public hidebysig instance !!T Get1<T> () cil managed
{
.maxstack 8
call !!0 [mscorlib]System.Activator::CreateInstance<!!T>()
ret
}
.method public hidebysig instance !!T Get2<.ctor T> () cil managed
{
.maxstack 8
call !!0 [mscorlib]System.Activator::CreateInstance<!!T>()
ret
}
为什么使用new()
约束的代码不能编译为下面的虚构代码?
.method public hidebysig instance !!T Get2<.ctor T> () cil managed
{
.maxstack 1
newobj instance void !!0::.ctor()
ret
}
约束<.ctor T>
是否意味着类型T
上必须有一个无参数的构造函数,因此像上面所示的那样调用它不应该吗?
当为.NET Framework 4.8和.NET Core(x64)以及最新版本(2019年9月23日)的Roslyn编译器进行编译时,会发生上述行为。