是否有解析字符串来创建C#func的工具? [英] Is there a tool for parsing a string to create a C# func?
问题描述
我需要知道是否有任何库允许我给定一个表示数学函数的字符串,比如 x ^ 2 + x + 1
,(不关心字符串格式是如何工作的)生成一个C#func来表示这个函数。
I need to know if there is any library out there that will allow me to, given a certain string representing a mathematical function, say, x^2+x+1
, (don't care about how the string format, any will work for me) generates a C# func that will represent said function.
推荐答案
现在一直在使用FLEE(快速轻量级表达式评估器),并且它一直在运行良好。他们有一个版本可以保持Silverlight的大部分功能。它的目的是为了完成你所要求的内容和更多内容。
Been using FLEE (Fast Lightweight Expression Evaluator) for a while now and it's been working great. They have a version that maintains most functionality for Silverlight as well. It's designed to do pretty much exactly what you're asking for and more.
Flee是.NET的表达式解析器和评估器框架。它
允许您在运行时计算字符串表达式的值,例如sqrt(a ^ 2
+ b ^ 2)。它使用自定义编译器,强类型表达式语言和轻量级代码编译器将表达式
直接编译为IL。这意味着表达式评估非常快速且高效。
Flee is an expression parser and evaluator for the .NET framework. It allows you to compute the value of string expressions such as sqrt(a^2 + b^2) at runtime. It uses a custom compiler, strongly-typed expression language, and lightweight codegen to compile expressions directly to IL. This means that expression evaluation is extremely fast and efficient.
考虑到您评论中的例子以评估 x ^ 2 + x + 1
(写在记事本中):
Given your example from your comment to evaluate x^2+x+1
(written in Notepad):
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
这篇关于是否有解析字符串来创建C#func的工具?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!