Runtime creation of generic Func<T>

和自甴很熟 提交于 2019-11-30 06:54:16

You use Delegate.CreateDelegate, i.e. from a MethodInfo; below, I've hard-coded, but you would use some logic, or Expression, to get the actual creation method:

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();
    }
}

For non-static methods, there is an overload of Delegate.CreateDelegate that accepts the target instance.

I think the usual approach would be to make the "dumb" version be the thing that you spoof at runtme, and then provide a helper extension method to provide the type-safe version on top of it.

you could create Expression objects instead of a func, and compile() the expression to get a Func delegate.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!