C#4.0'dynamic'不设置ref / out参数 [英] C# 4.0 'dynamic' doesn't set ref/out arguments

查看:141
本文介绍了C#4.0'dynamic'不设置ref / out参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 DynamicObject 。我尝试做的一件事是设置 ref / out 参数的值,如下面的代码所示。但是,我不能在 Main()中的 i j 正确设置(即使它们在 TryInvokeMember()中正确设置)。有人知道如何调用 DynamicObject 对象与 ref / out 参数,并能够检索方法中设置的值?

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:
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都确认:它已经修复了。

Update 9/8/2012: Tested using VS.NET 2012 with both .NET 4.0 and 4.5, confirm: it's already fixed.

推荐答案

这看起来像可以成为一个bug - 可能在 DynamicObject 中。如果您将 Wrap 方法添加到代理,如下所示:

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);
}

即使这仍然被动态调用(即 Main 保持不变)代码工作...所以至少一般动态对象的工作层支持传递引用。

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修复可能还为时太晚 - 但值得一提的是, Connect ,所以它可以修复到Service Pack中。或者,如果这是一个故意的限制/限制,应该在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'dynamic'不设置ref / out参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆