DynamicObject隐式转换 [英] DynamicObject implicit casting

查看:95
本文介绍了DynamicObject隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有DynamicObject的子类,我想实现的基本类型类似于DO的明确铸造方法TryConvert隐式转换;也就是说,无需编写多个隐式操作符【类型】功能

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.

用法:

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



这是可能的,如果是这样,怎么样?

Is that possible and if so, how?

推荐答案

有几件事情怎么回事。

首先,您要执行二进制操作。所以,你需要重写 TryBinaryOperation 方法为好。它会先调用,转换之前。然后从TryBinaryOperation方法,你可以执行转换

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.

二,无论出于何种原因只有当你写一份声明中这样的TryBinaryOperation被称为:

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

int sum = myDynamicObject + 1;



从我现在看到的顺序很重要。我会检查与DLR团队是否是一个错误或预期的行为

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

更新:
这是不是一个错误。同时支持的1 + myDynamicObject和myDynamicObject + 1的需要不仅TryBinaryOperation,而且像TryBinaryOperationFromRight,其中电流DynamicObject根本没有

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.

这篇关于DynamicObject隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆