简体   繁体   English

C#RealProxy:泛型方法?

[英]C# RealProxy: generic methods?

I'm trying to handle a call of a generic method through a RealProxy , but I cannot seem to find the information about the actual type of the generic parameter used in the intercepted method call. 我正在尝试通过RealProxy处理泛型方法的调用,但我似乎无法找到有关截获的方法调用中使用的泛型参数的实际类型的信息。 An excerpt of the code: 代码的摘录:

    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);
        ...

Let's say I'm proxying an interface like 假设我代理了一个类似的界面

interface IFactory
{
   TService Create<TService>()
}

When I call the proxy 当我打电话给代理

proxied.Create<MyClass>()

I want to be able to find out the generic parameter is of type MyClass . 我希望能够找到类型为MyClass的泛型参数。 Is this possible through RealProxy ? 这可以通过RealProxy吗?

There is an excellent MSDN article about RealProxy which I recommend you read. 一篇关于RealProxy的优秀MSDN文章 ,我建议你阅读。 Among other things, it introduces MethodCallMessageWrapper which saves you the trouble of working directly against the Properties dictionary. 除此之外,它引入了MethodCallMessageWrapper ,它MethodCallMessageWrapper直接使用Properties字典的麻烦。 From the latter you can get the MethodBase , which in turn contains the generic arguments: 从后者可以获得MethodBase ,而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(...);
  }

  ...
}

For method calls, the IMessage argument should be a IMethodMessage , which has a MethodBase property: 对于方法调用, 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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM