我正在试验DynamicObject.我尝试做的一件事是设置ref / out参数的值,如下面的代码所示.但是,我无法在Main()中正确设置i和j的值(即使在TryInvokeMember()中设置正确).有没有人知道如何使用ref / out参数调用DynamicObject对象,并能够检索方法中设置的值?
class Program { static void Main(string[] args) { dynamic proxy = new Proxy(new Target()); int i = 10; int j = 20; proxy.Wrap(ref i,ref j); Console.WriteLine(i + ":" + j); // Print "10:20" while expect "20:10" } } class Proxy : DynamicObject { private readonly Target target; public Proxy(Target target) { this.target = target; } public override bool TryInvokeMember(InvokeMemberBinder binder,object[] args,out object result) { int i = (int) args[0]; int j = (int) args[1]; target.Swap(ref i,ref j); args[0] = i; args[1] = j; result = null; return true; } } class Target { public void Swap(ref int i,ref int j) { int tmp = i; i = j; j = tmp; } }
更新7/15:
Microsoft声称已经解决了下一个版本的.NET http://connect.microsoft.com/VisualStudio/feedback/details/543101/net-4-0s-dynamicobject-doesn-t-set-ref-out-arguments的问题
更新9/8/2012:
使用VS.NET 2012和.NET 4.0和4.5进行测试,确认:它已经修复.