通過給出的求值運算公式字串得到其結果值
在實際開發中有時需要根據使用者制定的公式然後經過處理並將數值代替引數後來得出此公式的值,因為剛好也做到這裡,看了些資料,於是寫了一個類呼叫來實現此功能
using System;
using System.Text;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;
public class Evaluator {
object _compiled = null;
private string m_formula;
/// <summary>
/// 計算公式
/// </summary>
public string Formula{
get{
return m_formula;
}
set{
m_formula = value;
}
}
public Evaluator() {
}
public Evaluator(string formula){
Formula = formula;
}
public Double Execute(){
if(Formula == null || Formula == ""){
throw new Exception("請先設定Formula屬性!");
}
return this.Execute(Formula);
}
public Double Execute(string formula){
constructEvaluator(formula);
MethodInfo m = _compiled.GetType().GetMethod("GetValue");
return (Double)m.Invoke(_compiled, null);
}
private void constructEvaluator(string formula) {
ICodeCompiler compiler = (new CSharpCodeProvider().CreateCompiler());
CompilerParameters cp = new CompilerParameters();
cp.ReferencedAssemblies.Add("system.dll");
cp.GenerateExecutable = false;
cp.GenerateInMemory = true;
StringBuilder str = new StringBuilder();
str.Append("using System; /n");
str.Append("namespace Stoway { /n");
str.Append("public class Formula { /n");
str.AppendFormat(" public {0} GetValue()","Double");
str.Append("{");
str.AppendFormat(" return Convert.ToDouble({0}); ", formula);
str.Append("}/n");
str.Append("}/n");
str.Append("}");
CompilerResults cr = compiler.CompileAssemblyFromSource(cp, str.ToString());
if (cr.Errors.HasErrors) {
throw new Exception("不是正確的表示式");
}
Assembly a = cr.CompiledAssembly;
_compiled = a.CreateInstance("Stoway.Formula");
}
public static Double GetValue(string formula){
return new Evaluator().Execute(formula);
}
}
-----------
呼叫方法:
Evaluator evaluator = new Evaluator();
Double num = evaluator.Execute("( 3 + 5 ) * 2 + 56 / 0.25");
也可以:
Double num = Evaluator.GetValue("( 3 + 5 ) * 2 + 56 / 0.25");
-------------------------------------------------------