通过RealProxy引用参数

时间:2010-06-20 23:35:46

标签: c# reference arguments realproxy

我需要通过RealProxy调用带有ref-arguments的方法。我已将问题分解为以下代码:

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参数的修改在代理中丢失。我该怎么办才能让它发挥作用?

1 个答案:

答案 0 :(得分: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);
}
相关问题