【发布时间】:2016-04-11 10:27:37
【问题描述】:
我正在做一个将函数列表转换为 C# 代码的小项目。 例如:temp1.greaterThan(1); temp2.contains("a"); temp1、temp2 是字符串类型的表达式变量。 源代码为:
var temp1 = Expression.Variable(typeof(string), "temp1");
所以我想我需要将 temp1 转换为整数变量。 我尝试了以下方法,但没有奏效:
Expression greaterThan = Expression.GreaterThan(temp1, Expression.Constant(1));
它会抛出异常,因为 temp1 是字符串,因此不能与 1 比较。
Expression.GreaterThan(Expression.Call(typeof(int).GetMethod("Parse"), temp1), Expression.Constant(1));
它抛出“发现不明确的匹配”。异常
Expression.GreaterThan(Expression.Call(typeof(Convert).GetMethod("ToInt32"), temp1), Expression.Constant(1));
同样的例外:找到不明确的匹配项。
Expression.GreaterThan(Expression.Convert(temp1,typeof(Int32)), Expression.Constant(1));
例外:在类型“System.String”和“System.Int32”之间没有定义强制运算符。
所以我想我需要在 Expression.GreaterThan 方法中有一个转换方法。 有人有想法吗? 非常感谢。
【问题讨论】:
标签: c# string integer expression