次のようなコードがある場合:
static T GenericConstruct<T>() where T : new()
{
return new T();
}
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();
しかし、なぜこの回避策が必要なのか、私には理解できません。