gpt4 book ai didi

c# - 方法组中泛型调用的 RealProxy Invoke Message 中的 TargetException

转载 作者:太空狗 更新时间:2023-10-29 19:47:40 27 4
gpt4 key购买 nike

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

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 运气不好, 如何打开错误?

最佳答案

问题在这里:

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

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

尝试直接传递 _decorated 而不使用 this

关于c# - 方法组中泛型调用的 RealProxy Invoke Message 中的 TargetException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52734894/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com