DynamicObject 隐式转换

发布于 2024-08-18 05:31:59 字数 290 浏览 8 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

巴黎盛开的樱花 2024-08-25 05:31:59

这里发生了几件事。

首先,您正在执行二元运算。因此,您需要覆盖 TryBinaryOperation< /a> 方法也是如此。在转换之前它将首先被调用。然后,您可以从 TryBinaryOperation 方法执行转换。

其次,无论出于何种原因,仅当您编写如下语句时才会调用 TryBinaryOperation:

int sum = myDynamicObject + 1;

从我现在看来,顺序很重要。我将与 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:

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.

柏拉图鍀咏恒 2024-08-25 05:31:59

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文