我需要解析从string到bool的复杂表达式.
它只能包含:
*布尔值(true/false),
*括号,
*AND/OR操作数(&&,||)
例如:
bool.Parse("((true || false) && (false || false)) || (true || false)"
知道怎么做到这一点?
这是一个狡猾的求值程序类,它为您提供C#代码中的JScript.NET Eval函数:
static public class Evaluator { private const string _jscriptSource = @"package Evaluator { class Evaluator { public function Eval(expr : String) : String { return eval(expr); } } }"; static private object _evaluator; static private Type _evaluatorType; [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Can't be done inline - too complex")] static Evaluator() { InstantiateInternalEvaluator(); } static private void InstantiateInternalEvaluator() { JScriptCodeProvider compiler = new JScriptCodeProvider(); CompilerParameters parameters; parameters = new CompilerParameters(); parameters.GenerateInMemory = true; CompilerResults results; results = compiler.CompileAssemblyFromSource(parameters, _jscriptSource); Assembly assembly = results.CompiledAssembly; _evaluatorType = assembly.GetType("Evaluator.Evaluator"); _evaluator = Activator.CreateInstance(_evaluatorType); } static public int EvaluateToInteger(string statement) { string s = EvaluateToString(statement); return int.Parse(s); } static public double EvaluateToDouble(string statement) { string s = EvaluateToString(statement); return double.Parse(s); } static public decimal ForceEvaluateToDecimal(string statement) { decimal result; bool s = Decimal.TryParse(statement, out result); return result; } static public decimal EvaluateToDecimal(string statement) { string s = EvaluateToString(statement); return decimal.Parse(s); } static public string EvaluateToString(string statement) { object o = EvaluateToObject(statement); return o.ToString(); } static public bool EvaluateToBool(string statement) { object o = EvaluateToObject(statement); return (bool)o; } static public object EvaluateToObject(string statement) { try { return _evaluatorType.InvokeMember( "Eval", BindingFlags.InvokeMethod, null, _evaluator, new object[] {statement} ); } catch (Exception) { InstantiateInternalEvaluator(); return null; } } }
然后,您只需调用Evaluator.EvaluateToBool(string).从现有项目中取消,所以你可能想要调整!