C# - 如何与新的()约束GET机器代码生成的仿制药? [英] C# - How do generics with the new() constraint get machine code generated?
本文介绍了C# - 如何与新的()约束GET机器代码生成的仿制药?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public T Foo<T, U>(U thing) where T : new()
{
return new T();
}
在没有新()
的约束,我理解它是如何工作的。 JIT编译器看到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.
是如何工作的如果你在有新的T()?它在哪里找?
推荐答案
如果你的意思是,什么是IL样子,编译;在一个呼叫 Activator.CreateInstance< T>
If you mean, what does the IL look like, the compiler will compile in a call to Activator.CreateInstance<T>
.
您传递作为类型:T
必须有一个公共的无参数构造函数来满足编译器
The type you pass as T
must have a public parameterless constructor to satisfy the compiler.
您可以在尝试罗斯林:
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# - 如何与新的()约束GET机器代码生成的仿制药?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文