我需要将复杂表达式从字符串转换为布尔值。
它只能包含以下内容:
* 布尔值 (true/false),
* 括号,
* AND/OR 运算符 (&&, ||)
例如:
bool.Parse("((true || false) && (false || false)) || (true || false)"
有什么办法可以实现这个目标吗?
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)。该代码从现有项目中获取,因此您可能需要进行微调!
你所描述的字符串是有效的C#代码,因此如果你可以在运行时解释它,那么你就完成了。在许多语言中,这是一个内置函数。在C#中,它不是内置函数,但是你可以使用第三方库,例如这个运行时C#解释器
标准方法是: