作者:风情万种791008 | 来源:互联网 | 2022-12-02 16:42
假设我有一个通用接口 IService
和一个实现它的类Service : IService
我创建了该接口的代理:
var proxy = new DynamicProxy>(new Service()).GetTransparentProxy() as IService;
DynamicProxy是RealProxy的一个简单实现:
public class DynamicProxy : 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 bars = new List() { 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无法获得正确类型的泛型:
{Int32 Foo(System.__Canon)}
而不是IMethodCallMessage的MethodBase{Int32 Foo(Bar)}
这是方法组的限制吗?或RealProxy实现中的错误?
你可以在这里看到它:https:
//dotnetfiddle.net/w2VlVN
在MSDN论坛上没有运气,我怎么能打开一个bug?