【问题标题】:c# convert string to int in expression时间:2019-01-10 标签:c#convert string to int in expression
【发布时间】: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


    【解决方案1】:

    您应该使用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));
    

    【讨论】:

    • 非常感谢,正是我正在寻找的。​​span>
    猜你喜欢
    • 1970-01-01
    • 2011-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-13
    • 1970-01-01
    • 2017-07-09
    相关资源
    最近更新 更多