gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:15:14 25 4
gpt4 key购买 nike

我需要知道是否有任何库允许我给定一个表示数学函数的特定字符串,比如 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com