如果您有以下代码:
static T GenericConstruct<T>() where T : new()
{
return new T();
}
Run Code Online (Sandbox Code Playgroud)
C#编译器坚持发出对Activator.CreateInstance的调用,这比本机构造函数慢得多.
我有以下解决方法:
public static class ParameterlessConstructor<T>
where T : new()
{
public static T Create()
{
return _func();
}
private static Func<T> CreateFunc()
{
return Expression.Lambda<Func<T>>( Expression.New( typeof( T ) ) ).Compile();
}
private static Func<T> _func = CreateFunc();
}
// Example:
// Foo foo = ParameterlessConstructor<Foo>.Create();
Run Code Online (Sandbox Code Playgroud)
但是,为什么这个解决方案应该是必要的,这对我没有意义.
如果我有一个类型参数约束new():
void Foo<T>() where T : new()
{
var t = new T();
}
Run Code Online (Sandbox Code Playgroud)
在new T()内部使用该Activator.CreateInstance方法(即反射)是真的吗?
public T Foo<T, U>(U thing) where T : new()
{
return new T();
}
Run Code Online (Sandbox Code Playgroud)
当没有new()约束时,我理解它是如何工作的.JIT编译器看到T,如果它是引用类型,则使用代码的对象版本,并专门针对每个值类型的情况.
如果你有一个新的T(),它是如何工作的?它在哪里寻找?