可能重复:
Best and shortest way to evaluate mathematical expressions
如何使用C#在运行时运行字符串公式?
string formula = "10/2";
var result = Run(result);
感谢
答案 0 :(得分:0)
需要加载某种脚本引擎,然后将字符串传递给脚本引擎进行评估。
只需要知道哪种脚本语言使用。 Javascript,VbScript,Python等附件是Iron Python的链接和一些显示如何使用它的代码。使用VS2010 .Net 4。
using IronPython.Hosting;
using IronPython.Runtime;
//Script Engine Reference
using Microsoft.Scripting.Hosting;
//Source Code Kind Reference
using Microsoft.Scripting;
//Iron Python Reference
using IronPython.Hosting;
using IronPython.Runtime;
//Source Execute
using Microsoft.CSharp;
ScriptEngine engine = Python.CreateEngine();
ScriptRuntime runtime = engine.Runtime;
ScriptScope scope = runtime.CreateScope();
//Simple Example
string code = @"emp.Salary * 0.3";
ScriptSource source =
engine.CreateScriptSourceFromString(code, SourceCodeKind.Expression);
var emp = new Employee { Id = 1000, Name = "Bernie", Salary = 1000 };
scope.SetVariable("emp", emp);
var res = (double)source.Execute(scope);
MessageBox.Show(res.ToString());
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public double Salary { get; set; }
}