I'm working on a small project that transforms a list of functions into c# code. For example: temp1.greaterThan(1); temp2.contains("a"); temp1, temp2 are expression variables in string type. The source code is:
var temp1 = Expression.Variable(typeof(string), "temp1");
So I think I need to convert temp1 into an integer variable. I've tried following ways but none worked:
Expression greaterThan = Expression.GreaterThan(temp1, Expression.Constant(1));
It will throw exeption because temp1 is string and hence cannot compare with 1.
Expression.GreaterThan(Expression.Call(typeof(int).GetMethod("Parse"), temp1), Expression.Constant(1));
It throws "Ambiguous match found." exception
Expression.GreaterThan(Expression.Call(typeof(Convert).GetMethod("ToInt32"), temp1), Expression.Constant(1));
Same exception: Ambiguous match found.
Expression.GreaterThan(Expression.Convert(temp1,typeof(Int32)), Expression.Constant(1));
Exception: No coercion operator is defined between types 'System.String' and 'System.Int32'.
So I'm thinking i would need to have a convert method inside the Expression.GreaterThan method. Anyone has an idea? Many thanks.
You should use int.Parse
to parse a string instead of explicit conversion. Note that int.Parse
has a few overloads, that's why you get an "Ambiguous match found" exception.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With