我正在做一个将项目列表转换为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方法内有一个convert方法。有人有主意吗?非常感谢。
您应该使用int.Parse
解析字符串而不是显式转换。请注意,这里int.Parse
有一些重载,这就是为什么您会收到“发现歧义匹配”异常的原因。
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));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句