通用Func <T>的运行时创建

Cra*_*son 15 .net c# reflection

我需要实现这个方法:

object GetFactory(Type type);
Run Code Online (Sandbox Code Playgroud)

此方法需要返回一个Func <T>,其中typeparam'T'是'type'.

所以,我的问题是我不知道如何使用反射在运行时创建Func <?>.Activator.CreateInstance不起作用,因为委托上没有构造函数.

有任何想法吗?

Mar*_*ell 27

你使用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();
    }
}
Run Code Online (Sandbox Code Playgroud)

对于非静态方法,有一个Delegate.CreateDelegate接受目标实例的重载.