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

问题描述

我有一个DynamicObject的子类,我想实现隐式转换原始类型类似于DO的显式转换方法TryConvert;也就是说,没有编写多个隐式运算符[类型]函数。



用法:

  dynamic myDynamicObject = new MyDynamicObject(1); 
int sum = 1 + myDynamicObject; //而不是int i = 1 +(int)myDynamicObject;这是可能的,如果是这样,如何?

解决方案

这里有几件事情。



首先,执行二进制操作。因此,您需要替换方法。它将在转换前首先调用。然后从TryBinaryOperation方法可以执行转换。



其次,无论什么原因,TryBinaryOperation只有当你写这样的语句时才被调用:

  int sum = myDynamicObject + 1; 

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



更新:
这不是一个错误。要支持1 + myDynamicObject和myDynamicObject + 1,你不仅需要TryBinaryOperation,而且还需要TryBinaryOperationFromRight,而当前的DynamicObject根本没有。


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.

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

05-22 07:08