c#根据公式进行自动计算的实现
代码:
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Text;
using Microsoft.CSharp;
namespace Expression
{
/// <summary>
/// 计算表达式的类
/// </summary>
public class CalculateExpression
{
/// <summary>
/// 接受一个string类型的表达式并计算结果,返回一个object对象,静态方法
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public static object Calculate(string expression)
{
string className = "Calc";
string methodName = "Run";
expression = expression.Replace("/", "*1.0/");
//设置编译参数
CompilerParameters paras = new CompilerParameters();
paras.GenerateExecutable = false;
paras.GenerateInMemory = true;
//创建动态代码
StringBuilder classSource = new StringBuilder();
classSource.Append("public class " + className + "\n");
classSource.Append("{\n");
classSource.Append(" public object " + methodName + "()\n");
classSource.Append(" {\n");
classSource.Append(" return " + expression + ";\n");
classSource.Append(" }\n");
classSource.Append("}");
//编译代码
CompilerResults result = new CSharpCodeProvider().CompileAssemblyFromSource(paras, classSource.ToString());
//获取编译后的程序集。
Assembly assembly = result.CompiledAssembly;
//动态调用方法。
object eval = assembly.CreateInstance(className);
MethodInfo method = eval.GetType().GetMethod(methodName);
object reobj = method.Invoke(eval, null);
GC.Collect();
return reobj;
}
}
}
using System.CodeDom.Compiler;
using System.Reflection;
using System.Text;
using Microsoft.CSharp;
namespace Expression
{
/// <summary>
/// 计算表达式的类
/// </summary>
public class CalculateExpression
{
/// <summary>
/// 接受一个string类型的表达式并计算结果,返回一个object对象,静态方法
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public static object Calculate(string expression)
{
string className = "Calc";
string methodName = "Run";
expression = expression.Replace("/", "*1.0/");
//设置编译参数
CompilerParameters paras = new CompilerParameters();
paras.GenerateExecutable = false;
paras.GenerateInMemory = true;
//创建动态代码
StringBuilder classSource = new StringBuilder();
classSource.Append("public class " + className + "\n");
classSource.Append("{\n");
classSource.Append(" public object " + methodName + "()\n");
classSource.Append(" {\n");
classSource.Append(" return " + expression + ";\n");
classSource.Append(" }\n");
classSource.Append("}");
//编译代码
CompilerResults result = new CSharpCodeProvider().CompileAssemblyFromSource(paras, classSource.ToString());
//获取编译后的程序集。
Assembly assembly = result.CompiledAssembly;
//动态调用方法。
object eval = assembly.CreateInstance(className);
MethodInfo method = eval.GetType().GetMethod(methodName);
object reobj = method.Invoke(eval, null);
GC.Collect();
return reobj;
}
}
}
调用:
object objCalc = Calculate("((1 + 2) * 3 + 6) / 5 ");
Console.WriteLine(objCalc.ToString()); //结果为3
Console.ReadLine();
Console.WriteLine(objCalc.ToString()); //结果为3
Console.ReadLine();
注意点:
1、不支持sin、cos等数学函数2、不支持[]、{}等括号和除数字、+、-、*、/以外的字符,建议调用计算函数前进行输入的验证。
转自:http://hi.baidu.com/programed/item/f43cc6d43c6f3848fa576875