如果您不介意使用其中一种 .NET 语言编写代码,则可以使用 CodeDom 即时编译代码,然后将其作为仅内存程序集执行。例如,这将是您展示的示例表达式的最接近的近似值:
private abstract class Logic
{
protected double FVAL(object arg)
{
// put code here
return 0;
}
protected double ORGVAL(object arg)
{
// put code here
return 0;
}
protected double ORGVAL(object arg, string date)
{
// put code here
return 0;
}
public abstract double GetValue(object PFC, object BAS, object DA);
}
private class DynamicLogic : Logic
{
public override double GetValue(object PFC, object BAS, object DA)
{
return (FVAL(PFC) = true ? ((ORGVAL(BAS, "2012/12/31") + ORGVAL(DA)) < 6500 ? (FVAL(BAS) + FVAL(DA)) * .12 : 780) : 0);
}
}
private Logic GenerateLogic(string code)
{
using (CSharpCodeProvider provider = new CSharpCodeProvider())
{
StringBuilder classCode = new StringBuilder();
classCode.AppendLine("private class DynamicLogic : Logic");
classCode.AppendLine(" {");
classCode.AppendLine(" public override int GetValue(object PFC, object BAS, object DA)");
classCode.AppendLine(" {");
classCode.AppendLine(" return (" + code + ");");
classCode.AppendLine(" }");
classCode.AppendLine(" }");
CompilerParameters p = new CompilerParameters();
p.GenerateInMemory = true;
p.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
CompilerResults results = provider.CompileAssemblyFromSource(p, code);
return (Logic)Activator.CreateInstance(type);
if (results.Errors.HasErrors)
{
throw new Exception("Failed to compile DynamicLogic class");
}
return (Logic)results.CompiledAssembly.CreateInstance("DynamicLogic");
}
}
private double evaluate(object PFC, object BAS, object DA)
{
Logic logic = GenerateLogic("FVAL(PFC) = true ? ((ORGVAL(BAS, \"2012/12/31\") + ORGVAL(DA)) < 6500 ? (FVAL(BAS) + FVAL(DA)) * .12 : 780) : 0");
return logic.GetValue(PFC, BAS, DA);
}
编辑:我知道你说你需要真正得到表达式三,它本身,不仅仅是评估它,而是我处理了代码,所以我想我会继续并将它发布给未来的路人。