使用运行时已知类型调用泛型方法的快速方法

时间:2015-02-02 15:19:15

标签: c# reflection

我在编译时创建了一些我不知道的类型实例。对于这种方法,我搜索了另一种方法,然后使用Activator.CreateInstance,因为在开发过程中实例的数量可能会大量增加。我找到this帖子来快速创建这些实例。我唯一的问题是我不知道在编译时创建实例的实际类型。当然我可以使用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) { /* ... */ }
}

1 个答案:

答案 0 :(得分:1)

保留从Type到生成的Action<...>的字典,以快速调用您的方法。然后,调用开销是字典查找,它比基于反射的调用要小得多。

相关问题