如何创建功能以编程方式委托 [英] How to create a Func<> delegate programmatically

查看:104
本文介绍了如何创建功能以编程方式委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小的依赖项注入框架,并且我试图使它动态地解析Lazy<>实例.想法是做这样的事情:

I have a small dependency injection framework, and I am trying to make it resolve Lazy<> instances dynamically. The idea is to do something like that:

DIContainer.Register<IDbCommand,SqlCommand>();

var lazyCommand = DIContainer.Resolve<Lazy<IDbCommand>>();

前几天,我读到Autofac能够做到这一点.

I read the other day that Autofac was able of doing that.

我一直在尝试为该Lazy<>实例设置构造函数.在下一个测试代码中,抛出异常,因为所需的类型构造函数期望Func<arg>,但是我传递了Func<Object>:

I am stuck trying to set the constructor for that Lazy<> instance. In the next test code, a exception is thrown because the desired type constructor is expecting a Func<arg>, but I am passing a Func<Object>:

    static readonly Type _lazyType = typeof(Lazy<>);
    static Object ResolveTest(Type type)
    {
        if (type.IsGenericType && type.GetGenericTypeDefinition() == _lazyType)
        {
            var arg = type.GetGenericArguments()[0];

            return Activator.CreateInstance(_lazyType.MakeGenericType(arg), new Func<Object>(() => ResolveType(arg)));
        }
        else 
            return ResolveType(type);
    }

我不知道如何创建适合Lazy<>构造函数参数的委托.有什么主意吗?

I am out of ideas about how to create a delegate that fits for the Lazy<> constructor parameter. Any idea?

干杯.

推荐答案

那不是小事.一种可能的解决方案是使用反射:

That's not trivial. One possible solution would be to work with reflection:

  1. 创建通用的ResolveType方法:

public static T ResolveType<T>()
{
    return (T)ResolveType(typeof(T));
}

  • 创建使用此方法的委托:

  • Create a delegate that uses this method:

    // You probably want to cache this MethodInfo:
    var method = typeof(TypeContainingResolveType)
                     .GetMethods()
                     .Single(x => x.IsGenericMethod && 
                                  x.Name == "ResolveType")
                     .MakeGenericMethod(arg);
    
    var delegate = Delegate.CreateDelegate(
                       typeof(Func<>).MakeGenericType(arg),
                       method);
    

  • 使用该代表:

  • Use that delegate:

    return Activator.CreateInstance(_lazyType.MakeGenericType(arg), delegate);
    

  • 这篇关于如何创建功能以编程方式委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆