代码之家  ›  专栏  ›  技术社区  ›  Craig Wilson

泛型函数的运行时创建<T>

  •  15
  • Craig Wilson  · 技术社区  · 16 年前

    我需要实现以下方法:

    object GetFactory(Type type);
    

    所以,我的问题是我不知道如何创建Func<&燃气轮机;在运行时使用反射。Activator.CreateInstance无法工作,因为委托上没有构造函数。

    有什么想法吗?

    3 回复  |  直到 16 年前
        1
  •  29
  •   Marc Gravell    16 年前

    Delegate.CreateDelegate ,即从 MethodInfo ; 下面,我已经硬编码了,但是您可以使用一些逻辑,或者 Expression ,以获取实际的创建方法:

    using System;
    using System.Reflection;
    class Foo {}
    
    static class Program
    {
        static Func<T> GetFactory<T>()
        {
            return (Func<T>)GetFactory(typeof(T));
        }
        static object GetFactory(Type type)
        {
            Type funcType = typeof(Func<>).MakeGenericType(type);
            MethodInfo method = typeof(Program).GetMethod("CreateFoo",
                BindingFlags.NonPublic | BindingFlags.Static);
            return Delegate.CreateDelegate(funcType, method);
        }
        static Foo CreateFoo() { return new Foo(); }
        static void Main()
        {
            Func<Foo> factory = GetFactory<Foo>();
            Foo foo = factory();
        }
    }
    

    对于非静态方法,存在 Delegate.CreateDelegate

        2
  •  0
  •   Daniel Earwicker    16 年前

        3
  •  0
  •   Joachim Kerschbaumer    16 年前

    可以创建表达式对象而不是func,然后编译()表达式以获得func委托。

        4
  •  0
  •   Striped    4 年前

    var someType = SomeDbContext.SomeDataModelExample.GetType();
    var funcType1 = typeof(Func<>).MakeGenericType(new Type[] { someType });
    var result = Activator.CreateInstance(funcType1);
    var result2 = Activator.CreateInstance(funcType1, someParams);