开发者

DynamicObject implicit casting

开发者 https://www.devze.com 2022-12-16 19:05 出处:网络
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 开发者_高级运维mul

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?


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.


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 (+,-,...).

0

精彩评论

暂无评论...
验证码 换一张
取 消