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

后端 未结 3 1168
灰色年华
灰色年华 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: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.

提交回复
热议问题