使用CodeDom,实例公式自定义。初级,只实现算数表达式。
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
...
/// <summary>
/// 自定义公式DEMO
/// </summary>
/// <param name="express">算数表达式,如: 1/2.0 </param>
/// <returns>算数式的值。</returns>
private object MyEval(string express)
{
object ret = null;
StringBuilder code = new StringBuilder();
CodeDomProvider comp = new Microsoft.CSharp.CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters();
System.Reflection.MethodInfo mi;
code.Append("using System;/n");
code.Append("public class UserFunction{public static object UserFunction1(){return (");
code.Append(express);
code.Append(");}}");
cp.ReferencedAssemblies.Add("System.dll");
cp.GenerateExecutable = false;
cp.GenerateInMemory = true;
System.CodeDom.Compiler.CompilerResults cr = comp.CreateCompiler().CompileAssemblyFromSource(cp, code.ToString());
System.Reflection.Assembly asm;
Type t;
if (!cr.Errors.HasErrors)
{
asm = cr.CompiledAssembly;
t = asm.GetType("UserFunction");
mi = t.GetMethod("UserFunction1");
ret = mi.Invoke(null,null);
}
return ret;
}
有时间添加Math里面的复杂算数计算!