2010-06-20 3 views
2

Мне нужно вызвать метод с ref-аргументами через RealProxy. Я выделил проблему до следующего кода:Аргумент аргумента через RealProxy

using System; 
using System.Reflection; 
using System.Runtime.Remoting.Messaging; 
using System.Runtime.Remoting.Proxies; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      HelloClass hello=new HelloClass(); 
      TestProxy proxy = new TestProxy(hello); 
      HelloClass hello2 = proxy.GetTransparentProxy() as HelloClass; 

      string t = ""; 
      hello2.SayHello(ref t); 
      Console.Out.WriteLine(t); 
     } 
    } 

    public class TestProxy : RealProxy 
    { 
     HelloClass _hello; 

     public TestProxy(HelloClass hello) 
      : base(typeof(HelloClass)) 
     { 
      this._hello = hello; 
     } 

     public override System.Runtime.Remoting.Messaging.IMessage Invoke(System.Runtime.Remoting.Messaging.IMessage msg) 
     { 
      IMethodCallMessage call = msg as IMethodCallMessage; 
      object returnValue = typeof(HelloClass).InvokeMember(call.MethodName, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, _hello, call.Args); 
      return new ReturnMessage(returnValue, null, 0, call.LogicalCallContext, call); 
     } 
    } 

    public class HelloClass : MarshalByRefObject 
    { 
     public void SayHello(ref string s) 
     { 
      s = "Hello World!"; 
     } 
    } 
} 

Программа должна создать «Hello World!». вывода, но каким-то образом модификация аргументов ref теряется в прокси. Что я должен сделать, чтобы заставить это работать?

ответ

7

Второй параметр ReturnMessage должен содержать значения параметров ref и out для возврата. Вы можете получить их, сохранив ссылку на массив, в котором вы проходите:

public override System.Runtime.Remoting.Messaging.IMessage Invoke(System.Runtime.Remoting.Messaging.IMessage msg) 
{ 
    IMethodCallMessage call = msg as IMethodCallMessage; 
    var args = call.Args; 
    object returnValue = typeof(HelloClass).InvokeMember(call.MethodName, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, _hello, args); 
    return new ReturnMessage(returnValue, args, args.Length, call.LogicalCallContext, call); 
} 
+0

Большое вам спасибо! Это было очень полезно. – Guge

+0

Спасибо, он работал как шарм – phuongnd

Смежные вопросы