DynamicObject 隐式转换
我有一个 DynamicObject 的子类,我想为原始类型实现隐式转换,类似于 DO 的显式转换方法 TryConvert;也就是说,无需编写多个隐式运算符 [type] 函数。
用法:
dynamic myDynamicObject = new MyDynamicObject("1");
int sum = 1 + myDynamicObject; // instead of int i = 1 + (int)myDynamicObject;
这可能吗?如果可以,如何实现?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里发生了几件事。
首先,您正在执行二元运算。因此,您需要覆盖 TryBinaryOperation< /a> 方法也是如此。在转换之前它将首先被调用。然后,您可以从 TryBinaryOperation 方法执行转换。
其次,无论出于何种原因,仅当您编写如下语句时才会调用 TryBinaryOperation:
从我现在看来,顺序很重要。我将与 DLR 团队核实这是否是错误或预期行为。
更新:
这不是一个错误。要同时支持“1 + myDynamicObject”和“myDynamicObject + 1”,您不仅需要 TryBinaryOperation,还需要像 TryBinaryOperationFromRight 这样的东西,而当前的 DynamicObject 根本没有。
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:
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 团队回答了我的问题,并表示当 DO 是右侧操作数时这是不可能的。
引用他们的回答:
“最重要的规则是动态对象必须是左侧操作数,因为动态操作协议仅适用于该位置的动态对象。”
左手隐式转换可以通过 TryBinaryOperation 完成,但为此您还必须实现支持的运算符(+、-、...)。
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 (+,-,...).