如何在C#中将字符串公式转换为数学公式

4 c#

如果我有一个带有公式的字符串变量:

string myformula = "3 * 5 + Pow(2,3)";
Run Code Online (Sandbox Code Playgroud)

如何将此字符串转换为编译器可以计算的数学公式?

小智 9

最后,我为此目的获得了FLEE库.该工具是免费的,非常适合您的目的.以下是如何使用此库的示例:

// Define the context of our expression
ExpressionContext context = new ExpressionContext();
// Allow the expression to use all static public methods of System.Math
context.Imports.AddType(typeof(Math));
// Define an int variable
context.Variables["a"] = 100;
// Create a dynamic expression that evaluates to an Object
IDynamicExpression eDynamic = context.CompileDynamic("sqrt(a) + pi");
// Evaluate the expressions
double result = (double)eDynamic.Evaluate();
Run Code Online (Sandbox Code Playgroud)