评估条件表达式 [英] Evaluate Conditional Expression
问题描述
我在这,我救了我的如果条件,数据库作为一个字符串的情况。例如:
I have a scenario in which I am saving my "if" conditions in database as a string. For example:
String condition = "(([age] >= 28) && ([nationality] == 'US'))";
或
String condition = "([age] >= 28)";
现在,我要评估该用户已输入条件的语法的正确。这些例子语法不正确的:
Now, I want to evaluate that the user has input the condition syntactically correct. These are example of incorrect syntax:
String condition = "(([age] >= 28) && ([nationality] == 'US')"; //Missed ')' bracket
String condition = "[age] >= 28)"; //Missed Opening bracket '('
就像我们在评估查询表达式。可能是表达可以发辫。?有帮助但如何需要在这方面提供帮助。
Like we have in Evaluate Query Expression. Might be Expression tress can be helpful. But how? Need help in this regard.
推荐答案
看看的 NCalc ,它是用于评估数学表达式的框架。
Take a look at NCalc. It's a framework for evaluating mathematical expressions.
在表达式有语法错误,评估将抛出一个EvaluationException。
When the expression has a syntax error, the evaluation will throw an EvaluationException.
try
{
new Expression("(3 + 2").Evaluate();
}
catch(EvaluationException e)
{
Console.WriteLine("Error catched: " + e.Message);
}
不过,您也可以在评估前使用 HasErrors检测语法错误( 。)
法
Though, you can also detect syntax errors before the evaluation by using the HasErrors()
method.
Expression e = new Expression("a + b * (");
if(e.HasErrors())
{
Console.WriteLine(e.Error);
}
这篇关于评估条件表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!