C#4.0“动态”不设置REF /输出变量 [英] C# 4.0 'dynamic' doesn't set ref/out arguments
问题描述
我与 DynamicObject
实验。其中一件事我尝试做的是设置参考值
/ 的值了
参数,如$ C所示低于$ C。但是,我不能让值 I
和Ĵ
在的Main()
设置正确(即使它们在 TryInvokeMember设置正确()
)。有谁知道如何调用与 REF A
/ DynamicObject
对象退出
参数,并能够检索方法内部设定的值?
I'm experimenting with DynamicObject
. One of the things I try to do is setting the values of ref
/out
arguments, as shown in the code below. However, I am not able to have the values of i
and j
in Main()
set properly (even though they are set correctly in TryInvokeMember()
). Does anyone know how to call a DynamicObject
object with ref
/out
arguments and be able to retrieve the values set inside the method?
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
更新2012年9月8日:
使用VS.NET 2012既.NET 4.0和4.5,经测试证实:它已经固定
Update 9/8/2012: Tested using VS.NET 2012 with both .NET 4.0 and 4.5, confirm: it's already fixed.
推荐答案
这看起来像它的可能的是一个错误 - 大概在 DynamicObject
。如果添加了裹
方法代理
是这样的:
This looks like it could be a bug - probably in DynamicObject
. If you add a Wrap
method to Proxy
like this:
public void Wrap(ref int x, ref int y)
{
target.Swap(ref x, ref y);
}
那么尽管这仍然是动态调用(即主要的code
保持不变)的code工作...所以至少一般的如何做一个动态对象的作品层支持传递通过引用。
Then even though this is still called dynamically (i.e. the code in Main
stays the same) the code works... so at least the general "how does a dynamic object work" layer supports pass-by-reference.
我怀疑,如果这的是的确实是一个在DLR错误,可能为时已晚修为.NET 4 - 但它是值得上的反正连接因此它可以固定在一个服务包。另外,如果这是一个刻意限制/限制,应明确在MSDN(它是不是现在,据我可以看到)。记录
I suspect if this is indeed a bug in the DLR, it may be too late to fix for .NET 4 - but it's worth reporting on Connect anyway so it can be fixed in a service pack. Alternatively, if this is a deliberate restriction/limitation, it should be clearly documented in MSDN (which it isn't at the moment, as far as I can see).
这篇关于C#4.0“动态”不设置REF /输出变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!