【问题标题】:Can I use Linfu dynamic proxy to proxy an interface with generic parameters?可以使用林孚动态代理来代理带有泛型参数的接口吗?
【发布时间】:2012-11-22 14:07:24
【问题描述】:

我目前正在使用 Linfu 来创建动态代理,它对于普通接口非常有效。问题是我现在需要为具有通用参数的接口创建一个动态代理。直到运行时我才知道泛型参数的类型(甚至加载包含它们的程序集)。有谁知道这是否可能?

【问题讨论】:

    标签: c# dynamic-proxy linfu-dynamicproxy


    【解决方案1】:

    好的,我可以通过使用反射调用 MyProxyFactory.CreateProxy() 来做到这一点:

            Type myGenericParam1 = myParam1.GetType();
            Type myGenericParam2 = myParam2.GetType();
            Type myGenericInterfaceType = typeof(IMyInterface<,>);
            Type myActualInterfaceType = myGenericInterfaceType.MakeGenericType(myGenericParam1, myGenericParam2);
            var proxyObjectContainer = typeof(MyProxyFactory).GetMethod("CreateProxy", new Type[] { }).MakeGenericMethod(new[] { myActualInterfaceType }).Invoke(null, new object[] { });
    
            var proxyObject = proxyObjectContainer.GetType().GetProperty("Proxy").GetValue(proxyObjectContainer, null);
    

    显然,如果您需要将参数传递给代理工厂构造函数以设置拦截器,那么这也需要添加到创建 proxyObjectContainer 的行中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-18
      • 1970-01-01
      相关资源
      最近更新 更多