简体   繁体   English

评估字符串表达式并转换为布尔值?

[英]Evaluate string expression and convert to bool?

I want to evaluate the string expression and convert the result to bool.我想评估字符串表达式并将结果转换为 bool。

For example例如

string expression = !((71 > 70) && (80 > 71)) || 72 < 71 ;

the above expression has to evaluate and return true.上面的表达式必须求值并返回 true。

Can anyone suggest how to evaluate the expression and return bool value?谁能建议如何评估表达式并返回 bool 值?

I dont believe there is any built in expression solver that can be leveraged for this kind of expression evaluation.我不相信有任何内置的表达式求解器可以用于这种表达式评估。 I would recommend Microsoft.CodeAnalysis.CSharp.Scripting to do the evaluation.我会推荐Microsoft.CodeAnalysis.CSharp.Scripting进行评估。

string expression = "!((71 > 70) && (80 > 71)) || 72 < 71";
bool output = CSharpScript.EvaluateAsync<bool>(expression).Result;
// -> false

Issues with your question你的问题有问题

  • The expression will not evaluate to true.表达式不会评估为真。 I dont know why you assume that and require that it does.我不知道你为什么假设并要求它这样做。 After the execution of the above script, the resultant bool will be false.执行上述脚本后,得到的 bool 将为 false。

!((71 > 70) && (80 > 71)) || 72 < 71
!((true) && (true)) || false
!(true & true)
false

  • you cannot declare a string without quotes;你不能声明一个没有引号的字符串; string express = "within quotes"; . . Statement above in post ( string expression = !((71 > 70) && (80 > 71)) || 72 < 71 ; ) is not a valid C# statement.上面 post 中的语句 ( string expression = !((71 > 70) && (80 > 71)) || 72 < 71 ; ) 不是有效的 C# 语句。

Test snippet here at #dotnetfiddle #dotnetfiddle 的测试片段

You can use the NCalc package.您可以使用 NCalc 包。 The code below produces "False"下面的代码产生“假”

using System;
using NCalc;

public class Program
{
    public static void Main()
    {
        Expression e = new Expression("!((71 > 70) && (80 > 71)) || 72 < 71");
        bool v = (bool)e.Evaluate();
        Console.WriteLine(v.ToString());
    }
}

.Net Fiddle: https://dotnetfiddle.net/02c5ww .Net 小提琴: https : //dotnetfiddle.net/02c5ww

If your requirement is to get expressoin output as string "true" then use this,如果您的要求是将 expressoin 输出作为字符串“true”,则使用它,

string expression = Convert.ToString(!((71 > 70) && (80 > 71)) || 72 < 71);

And if requirement is to get bool "true" then use this,如果要求是让 bool “true”,则使用它,

bool expression = !((71 > 70) && (80 > 71)) || 72 < 71;

But your expression is like it will return false, to make it true remove "!"但是你的表达就像它会返回 false,要让它成为 true 删除“!” as below,如下,

string expression = Convert.ToString(((71 > 70) && (80 > 71)) || 72 < 71);            
bool bool_expression = ((71 > 70) && (80 > 71)) || 72 < 71;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM