我需要知道是否有任何库可以让我根据表示数学函数的某个字符串(例如,x^2+x+1
)生成一个代表该函数的 C# 函数(不关心字符串格式,任何格式都可以)。
我需要知道是否有任何库可以让我根据表示数学函数的某个字符串(例如,x^2+x+1
)生成一个代表该函数的 C# 函数(不关心字符串格式,任何格式都可以)。
我已经使用FLEE(快速轻便表达式评估器)一段时间了,它一直表现出色。他们还提供了一个版本用于Silverlight保留大部分功能。它的设计几乎完全符合你所要求的,并且还可以做更多。
Flee是.NET框架的表达式解析器和评估器。它允许您在运行时计算字符串表达式的值,例如sqrt(a^2+b^2)。它使用自定义编译器、强类型表达式语言和轻量级代码生成来直接编译表达式为IL。这意味着表达式评估非常快速和高效。
给定您在评论中的示例x^2+x+1
(在记事本中编写):
public Func<double, double> CreateExpressionForX(string expression)
{
ExpressionContext context = new ExpressionContext();
// Define some variables
context.Variables["x"] = 0.0d;
// Use the variables in the expression
IDynamicExpression e = context.CompileDynamic(expression);
Func<double, double> expressionEvaluator = (double input) =>
{
content.Variables["x"] = input;
var result = (double)e.Evaluate();
return result;
}
return expressionEvaluator;
}
Func<double, double> expression = CreateExpressionForX("x^2 + x + 1");
double result1 = expression(1); //3
double result2 = expression(20.5); //441.75
double result3 = expression(-10.5); //121.75
Func<double, double> expression2 = CreateExpressionForX("3 * x + 10");
double result4 = expression2(1); //13
double result5 = expression2(20.5); //71.5
double result6 = expression2(-10.5); //-21.5
可以看一下Roslyn API,它能够让你在运行时编译字符串。
您可以使用CodeDOM来动态编译类型,关于此,在这里您可以找到一个流畅的接口来简化代码编写,例如:
var compileUnit = new FluentCodeCompileUnit()
.Namespace("Sample1")
.Class("Program")
.Method(MemberAttributes.Public | MemberAttributes.Static, "Main").Parameter(typeof(string[]), "args")
.CallStatic(typeof(Console), "WriteLine", Expr.Primitive("Hello Fluent CodeDom"))
.EndMethod
.Method(MemberAttributes.Public | MemberAttributes.Static, "Linq2CodeDomSupport").Parameter(typeof(string[]), "args")
.Stmt(ExprLinq.Expr(() => Console.WriteLine("Hello Linq2CodeDOM")))
.Declare(typeof(int), "random", ExprLinq.Expr(() => new Random().Next(10)))
.If((int random) => random <= 5)
.Stmt(ExprLinq.Expr(() => Console.WriteLine("Smaller or equal to 5.")))
.Else
.Stmt(ExprLinq.Expr(() => Console.WriteLine("Bigger than 5.")))
.EndIf
.EndMethod
.EndClass
.EndNamespace
.EndFluent();
var assembly = Helper.CodeDomHelper.CompileInMemory(compileUnit);
assembly.GetType("Sample1.Program").GetMethod("Main").Invoke(null, new object[] { null });
我需要在CodePlex上发布一个更好的流畅接口API,它将在Roslyn发布RTM时使用。
eval
函数吗?https://dev59.com/pXVD5IYBdhLWcg3wWaVh http://www.codeproject.com/Articles/11939/Evaluate-C-Code-Eval-Function - Tim S.