日期:2014-05-18 浏览次数:20869 次
/// <summary> /// 采用动态编译,计算表达式的结果 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button6_Click(object sender, EventArgs e) { // 声明要计算C#代码,要求必须完整的C#代码 string strCode = @" using System; namespace ParseEx { public class ParseExC { public static double GetValue() { return 1+5*8-(Math.Sin(12)*2.5); } } }"; CodeDomProvider comp = new CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters(); StringBuilder codeBuilder = new StringBuilder(); codeBuilder.AppendLine(strCode); cp.ReferencedAssemblies.Add("System.dll"); cp.GenerateExecutable = false; cp.GenerateInMemory = true; CompilerResults cr = comp.CompileAssemblyFromSource(cp, codeBuilder.ToString()); if (cr.Errors.HasErrors) { MessageBox.Show("Error!"); } else { Assembly a = cr.CompiledAssembly; if (a != null) { Type t = a.GetType("ParseEx.ParseExC"); if (t != null) { // 因为是静态调用,不需要创建实例了 // object mode = a.CreateInstance("Mode"); MethodInfo mi = t.GetMethod("GetValue", BindingFlags.Static | BindingFlags.Public); if (mi != null) { double d = (double)mi.Invoke(null, null); MessageBox.Show(d.ToString()); } } } } }
------解决方案--------------------
使用CodeDom,微软提供的.net类,直接可以生成代码并编译,具体请MSDN