DynamicObject implicit casting

僤鯓⒐⒋嵵緔 提交于 2019-12-22 06:39:50

问题


I have a subclass of DynamicObject and I would like to implement implicit casting for primitive types similarly as DO's explicit casting method TryConvert; that is, without writing multiple implicit operator [type] functions.

Usage:

dynamic myDynamicObject = new MyDynamicObject("1");
int sum = 1 + myDynamicObject; // instead of int i = 1 + (int)myDynamicObject;

Is that possible and if so, how?


回答1:


There are several things going on here.

First, you are performing a binary operation. So, you need to override TryBinaryOperation method as well. It will be called first, before conversion. Then from the TryBinaryOperation method you can perform a conversion.

Second, for whatever reason the TryBinaryOperation is called only if you write a statement like this:

int sum = myDynamicObject + 1;

From what I see now, the order is important. I'll check with the DLR team whether it is a bug or intended behavior.

Update: It's not a bug. To support both "1 + myDynamicObject" and "myDynamicObject + 1" you need not only TryBinaryOperation, but also something like TryBinaryOperationFromRight, which the current DynamicObject simply does not have.




回答2:


DLR-team answered my question and said that it isn't possible when DO is the right-hand operand.

Quoted from their answer: "The foremost rule is that the dynamic object needs to be the left hand operand because the dynamic operations protocol only works with the dynamic object in that position."

Left-hand implicit casting can be done through TryBinaryOperation, but for that you have to also implement the supported operators (+,-,...).



来源:https://stackoverflow.com/questions/2075649/dynamicobject-implicit-casting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!