如果您有以下代码:
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)
但是,为什么这个解决方案应该是必要的,这对我没有意义.