我正在尝试通过RealProxy
处理泛型方法的调用,但我似乎无法找到有关截获的方法调用中使用的泛型参数的实际类型的信息。代码的摘录:
public override IMessage Invoke(IMessage msg)
{
...
string methodName = (string)msg.Properties["__MethodName"];
Type[] parameterTypes = (Type[])msg.Properties["__MethodSignature"];
object[] args = (object[])msg.Properties["__Args"];
MethodInfo method = typeToProxy.GetMethod(methodName, parameterTypes);
...
假设我代理的是
这样的界面interface IFactory
{
TService Create<TService>()
}
当我致电代理时
proxied.Create<MyClass>()
我希望能够找到类型为MyClass
的泛型参数。这可以通过RealProxy
吗?
答案 0 :(得分:6)
我建议您阅读有关RealProxy的优秀MSDN article。
除此之外,它还引入了MethodCallMessageWrapper
,这可以帮助您省去直接针对Properties
字典的麻烦。从后者可以获得MethodBase
,而internal class MyProxy : RealProxy
{
private object m_instance;
private MyProxy( object instance ) : base( typeof( IFactory) )
{
m_instance = instance;
}
public override IMessage Invoke( IMessage message )
{
IMethodCallMessage methodMessage =
new MethodCallMessageWrapper( (IMethodCallMessage) message );
// Obtain the actual method definition that is being called.
MethodBase method = methodMessage.MethodBase;
Type[] genericArgs = method.GetGenericArguments(); //This is what you want
return new ReturnMessage(...);
}
...
}
又包含通用参数:
{{1}}
答案 1 :(得分:3)
对于方法调用,IMessage
参数应为IMethodMessage
,其属性为MethodBase
:
public override IMessage Invoke(IMessage message)
{
IMethodMessage methodMessage = message as IMethodMessage;
if (methodMessage != null)
{
MethodBase method = methodMessage.MethodBase;
Type[] genericArgs = method.GetGenericArguments();
...
}
else
{
// not a method call
}
}