我想使用 Expression.Add
对两种数据类型求和,这可能是 double
和 int
(或任何其他不匹配的对),就像这样:
var pLeft = Expression.Parameter(typeof(int), "left");
var pRight = Expression.Parameter(typeof(double), "right");
var addition = Expression.Add(pLeft, pRight);
var lambda = Expression.Lambda<Func<int, double, double>>(addition, pLeft, pRight).Compile();
var res = method(1, 0.5);
但是,我立即被告知:
The binary operator Add is not defined for the types 'System.Int32' and 'System.Double'.
很明显,+
运算符并没有为每对可能的数字定义,但是当我写类似 var x = 1 + 0.5 的东西时,某种隐式转换会继续进行
。有没有一种方法可以使用表达式模拟这种转换,或者有一种方法可以使用表达式对这些类型求和?
最佳答案
使用 Expression.Convert
将其中一个参数转换为相反参数的类型。
表达式树对于隐式转换应该如何工作没有“意见”,因为它们不是特定于语言的。例如,C# 的隐式转换规则与 VB.NET 不同。表达式树采取中立立场并需要显式转换。
例如,一种面向性能的语言可能决定将 double 隐式转换为 int,因为默认情况下它更喜欢性能。在这种情况下,C# 更喜欢精度。表达式树一般不能解决这个问题。
关于c# - 如何使用 Expression.Add 对 double 和 int 求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11171471/