我正在尝试使用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: 微软声称已经在下一个.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,确认已经修复。