[csharp]
/// <summary>
/// 將字符串中的運算符按正常計算 例如按四則運算
/// </summary>
/// <param name="expression">標准表達式如 1+15*0.5-200</param>
/// <returns>返回計算的值,可以為任意合法的數據類型</returns>
protected static object MathCalculate(string expression)
{
object retvar = null;
Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
System.CodeDom.Compiler.CompilerParameters cp = new System.CodeDom.Compiler.CompilerParameters(
new string[] { @"System.dll" });
StringBuilder builder = new StringBuilder("using System;class CalcExp{public static object Calc(){ return \"expression\";}}");
builder.Replace("\"expression\"", expression);
string code = builder.ToString();
System.CodeDom.Compiler.CompilerResults results;
results = provider.CompileAssemblyFromSource(cp, new string[] { code });
if (results.Errors.HasErrors)
{
retvar = null;
}
else
{
System.Reflection.Assembly a = results.CompiledAssembly;
Type t = a.GetType("CalcExp");
retvar = t.InvokeMember("Calc", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod
, System.Type.DefaultBinder, null, null);
}
return retvar;
}