更新时间:2022-12-09 13:35:49
You can use Roslyn scripting API for that. Add Microsoft.CodeAnalysis.CSharp.Scripting package and evaluate C# code like this:
static async Task<double> EvaluateFormulaAsync(string formula)
{
return await CSharpScript.EvaluateAsync<double>(formula,
ScriptOptions.Default.WithImports("System.Math"));
}
用法:
var result = EvaluateFormulaAsync("Sqrt(2) + 2 * 15").Result; // 31.4142135623731
注意:脚本API需要.NET Framework 4.6+或.NET Core 1.1
Note: Scripting API requires .NET Framework 4.6+ or .NET Core 1.1