c# - 是否有用于解析字符串以创建 C# 函数的工具?

标签 c# string parsing function string-parsing

我需要知道是否有任何库允许我给定一个表示数学函数的特定字符串,比如 x^2+x+1,(不要关心字符串格式如何,任何对我有用)生成一个 C# 函数来表示所述函数。

最佳答案

使用 FLEE(快速轻量级表达式评估器)已有一段时间了,它运行良好。他们的版本也保留了 Silverlight 的大部分功能。它旨在完全满足您的要求,甚至更多。

http://flee.codeplex.com/

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(用记事本编写):

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# - 是否有用于解析字符串以创建 C# 函数的工具?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10864311/

相关文章:

c - 如何将字母从字符串中取出? C语言

c - 尝试使用 getopt 解析 c 中的输入

c# - 你调用的对象是空的?

javascript url 安全文件名安全字符串

c# - 在 .Net 中,出于性能原因,我什么时候应该通过引用传递结构?

python 参数 1 必须有一个 write 方法

parsing - 使用java 8中的流读取空格分隔的文本文件的第一列

javascript - 为什么这个javascript不解析?

c# - 如何在 MathNet.Symbolics Evaluate 函数中设置 double ?

c# - 当编码以 + 开头时,Base64 解码中断