方法组中通用类型调用的RealProxy调用消息中的TargetException

时间:2018-10-10 07:30:53

标签: c# generics reflection proxy remoting

假设我有一个通用接口IService<T>和一个实现该接口的类Service : IService<Bar> 我创建该接口的代理:

var proxy = new DynamicProxy<IService<Bar>>(new Service()).GetTransparentProxy() as IService<Bar>;

DynamicProxy是RealProxy的简单实现:

    public class DynamicProxy<I> : RealProxy
    {
        private I _decorated;

        public DynamicProxy(I decorated) : base(typeof(I))
        {
            this._decorated = decorated;
        }

        public override IMessage Invoke(IMessage msg)
        {
            IMethodCallMessage methodCall = (IMethodCallMessage)msg;
            MethodInfo methodInfo = methodCall.MethodBase as MethodInfo;

            return new ReturnMessage(
                methodInfo.Invoke(this._decorated, methodCall.InArgs),
                null,
                0,
                methodCall.LogicalCallContext,
                methodCall);
        }
    }

直接使用我的代理服务器时,它可以正常工作:

IEnumerable<Bar> bars = new List<Bar>() { new Bar { id = 2 }, new Bar { id = 3 } };
proxy.Foo(bars.First());

甚至使用lambda也可以:

 var data = bars.ToList().Select(bar => proxy.Foo(bar)).ToList();

但是当与方法组一起使用时,它会引发目标异常

var data = bars.ToList().Select(proxy.Foo).ToList();

抛出的异常:

{System.Reflection.TargetException: Object does not match target type.
   at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
   at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)

似乎realproxy无法设法获得正确的泛型类型:

IMethodCallMessage的MethodBase是{Int32 Foo(System.__Canon)}而不是{Int32 Foo(Bar)}

方法组的限制吗?还是RealProxy实施中的错误?

您可以在这里看到它: https://dotnetfiddle.net/w2VlVN

MSDN forum运气不好,我该如何打开错误?

1 个答案:

答案 0 :(得分:0)

问题在这里:

methodInfo.Invoke(this._decorated, methodCall.InArgs), 

这里的this参数是错误的,您需要直接调用您的类,而不是使用this

尝试直接通过_decorated,而不使用this