2、不支持[]、{}等括号和除数字、+、-、*、/以外的字符,建议调用计算函数前进行输入的验证。
using System;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using Microsoft.CSharp;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void simpleButton1_Click(object sender, EventArgs e)
{
int icnt = 0;
string[] ss = new string[100];
for (int i = 0; i < 4; i++)
{
string s = "5";
LinkString(i, ref s);
for (int j = 0; j < 4; j++)
{
string s2 = s;
LinkString(j, ref s2);
for (int m = 0; m < 4; m++)
{
string s3 = s2;
LinkString(m, ref s3);
ss[icnt] = s3 + " = " + Calculate(s3).ToString();
icnt++;
}
}
}
memoEdit1.Lines = ss;
}
private void LinkString(int i, ref string s)
{
if (i == 0)
s = s + " + 5";
else
if (i == 1)
s = s + " - 5";
else
if (i == 2)
s = s + " * 5";
else
s = s + " / 5";
}
/// <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/");
// 创建编译器实例。
ICodeCompiler complier = (new CSharpCodeProvider().CreateCompiler());
// 设置编译参数。
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 = complier.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;
}
}
}
结果如下: