C# 4.0 'dynamic' doesn't set ref/out arguments

后端 未结 3 1154
灰色年华
灰色年华 2020-12-03 17:51

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

相关标签:
3条回答
  • 2020-12-03 18:44

    To make a long story short, DynamicObject doesn't support pass-by-reference, so what you want to do is not directly possible.

    0 讨论(0)
  • 2020-12-03 18:45

    This is not a bug. As it was already said here, DynamicObject doesn't support ref and out parameters in TryInvokeMember. Everything passed to this method is treated "by value". Shortly, TryInvokeMember method simply ignores these keywords, and that is why your method doesn't work.

    If you follow Jon Skeet suggestion and create your own Wrap method within a class inherited from DynamicObject, this will be a little bit different scenario. The workflow looks like this: when there is a method call for DynamicObject, C# runtime binder first looks for the method in the class itself. If it can find one, it calls this method. At this point, information about "ref" and "out" parameters is still preserved. If it can't find such a method, it calls TryInvokeMember method and simply throws out information about "ref" and "out" keywords and starts treating everyting as "by value". Remember that DynamicObject has to suport interoperability with other language, which might not have all of the C# features.

    True, information about "ref" and "out" is now missing from documentation. I will add it to the next documenation update.

    0 讨论(0)
  • 2020-12-03 18:48

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

    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.

    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).

    0 讨论(0)
提交回复
热议问题