c#将表达式中的字符串转换为int

c# convert string to int in expression

我正在开发一个将函数列表转换为 C# 代码的小项目。 例如:temp1.greaterThan(1); temp2.contains("a"); temp1、temp2 是字符串类型的表达式变量。 源码为:

var temp1 = Expression.Variable(typeof(string), "temp1");   

所以我想我需要将temp1 转换成一个整型变量。 我尝试了以下方法,但 none 有效:

Expression greaterThan = Expression.GreaterThan(temp1, Expression.Constant(1));

它会抛出异常,因为 temp1 是字符串,因此无法与 1 进行比较。

Expression.GreaterThan(Expression.Call(typeof(int).GetMethod("Parse"), temp1), Expression.Constant(1));

它抛出 "Ambiguous match found." 异常

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 方法中有一个转换方法。 有人有想法吗? 非常感谢。

您应该使用int.Parse 来解析字符串而不是显式转换。请注意 int.Parse 有一些重载,这就是为什么你会得到 "Ambiguous match found" 异常。

var temp1 = Expression.Variable(typeof(string), "temp1");

//use int.Parse(string) here
var parseMethod = typeof(int).GetMethod("Parse", new[] { typeof(string) }); 

var gt = Expression.GreaterThan(Expression.Call(parseMethod, temp1), Expression.Constant(1));