我正在创建一些在编译时不知道的类型的实例。对于这种方法,我寻找了另一种方法,然后使用Activator.CreateInstance,因为在开发过程中实例的数量可能会大量增加。我发现this post可以快速创建这些实例。我唯一的问题是,我不知道在编译时创建实例的实际类型。当然,我可以使用MethodInfo.MakeGenericMethod(myType),然后使用method.Invoke来调用接收到的方法。但正如我在前面提到的文章中看到的,在构造函数上调用Invoke需要花费很多时间,所以我想知道这是否也适用于常见的方法。
因此,寻找一种快速的方法来构造一个类型的实例,而不是寻找接收该类型的最佳解决方案,这将是相当矛盾的。那么有没有类似的(可能也使用了表达式树)?
一些用于编辑的代码:
public delegate T ObjectActivator<T>(params object[] args);
public class Test
{
public object create(Type t)
{
// get the default-constructor
ConstructorInfo ctor = t.GetConstructors().First();
// pass the type to the generic method
MethodInfo method = typeof(GenericTypeFactory).GetMethod("GetActivator").MakeGenericMethod(t);
Func<ConstructorInfo, Delegate> getActivator = // howto point to the GetActivator-method by using the generic methodInfo from above
}
}
class GenericTypeFactory {
public static ObjectActivator<T> GetActivator<T>(ConstructorInfo ctor) { /* ... */ }
}发布于 2015-02-02 23:44:19
保存从Type到生成的Action<...>的字典,以便快速调用您的方法。因此,调用开销是字典查找,这比基于反射的调用要少得多。
https://stackoverflow.com/questions/28280911
复制相似问题