这是我过去使用的课程。就像eval()在Javascript中一样,它计算字符串。
String result = ExpressionEvaluator.EvaluateToString("(2+5) < 8");
您需要做的就是构造一个要从您的业务对象进行评估的字符串,这将处理所有复杂的嵌套逻辑等。
using System;
using System.CodeDom.Compiler;
using System.Globalization;
using System.Reflection;
using Microsoft.JScript;
namespace Common.Rule
{
internal static class ExpressionEvaluator
{
#region static members
private static object _evaluator = GetEvaluator();
private static Type _evaluatorType;
private const string _evaluatorSourceCode =
@"package Evaluator
{
class Evaluator
{
public function Eval(expr : String) : String
{
return eval(expr);
}
}
}";
#endregion
#region static methods
private static object GetEvaluator()
{
CompilerParameters parameters;
parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
JScriptCodeProvider jp = new JScriptCodeProvider();
CompilerResults results = jp.CompileAssemblyFromSource(parameters, _evaluatorSourceCode);
Assembly assembly = results.CompiledAssembly;
_evaluatorType = assembly.GetType("Evaluator.Evaluator");
return Activator.CreateInstance(_evaluatorType);
}
public static string EvaluateToString(string statement)
{
object o = EvaluateToObject(statement);
return o.ToString();
}
public static object EvaluateToObject(string statement)
{
lock (_evaluator)
{
return _evaluatorType.InvokeMember(
"Eval",
BindingFlags.InvokeMethod,
null,
_evaluator,
new object[] { statement },
CultureInfo.CurrentCulture
);
}
}
#endregion
}
}