C#动态编译计算
示例代码1:
using Microsoft.CSharp; using System; using System.CodeDom.Compiler; using System.Reflection; namespace ConsoleApp6 { internal class Program { private static void Main(string[] args) { Expression e = new Expression("x+5*9/3.2+6"); Console.WriteLine(e.Compute(10)); Console.Read(); } } public class Expression { private object instance; private MethodInfo method; /// <summary> /// 表达试运算 /// </summary> /// <param name="expression">表达试</param> public Expression(string expression) { if (expression.IndexOf("return") < 0) { expression = "return " + expression + ";"; } string className = "Expression"; string methodName = "Compute"; CompilerParameters p = new CompilerParameters(); p.GenerateInMemory = true; var source = string.Format("using System;sealed class {0}{{public double {1}(double x){{{2}}}}}", className, methodName, expression); CompilerResults cr = new CSharpCodeProvider().CompileAssemblyFromSource(p, source); if (cr.Errors.Count > 0) { string msg = "Expression(\"" + expression + "\"): \n"; foreach (CompilerError err in cr.Errors) { msg += err.ToString() + "\n"; } throw new Exception(msg); } instance = cr.CompiledAssembly.CreateInstance(className); method = instance.GetType().GetMethod(methodName); } /// <summary> /// 处理数据 /// </summary> /// <param name="x"></param> /// <returns>返回计算值</returns> public double Compute(double x) { return (double)method.Invoke(instance, new object[] { x }); } } }
示例代码2:
using System; using System.Reflection; using System.Globalization; using Microsoft.CSharp; using System.CodeDom; using System.CodeDom.Compiler; using System.Text; namespace ConsoleApplication1 { public class Program { private static void Main(string[] args) { // 1.CSharpCodePrivoder CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); // 3.CompilerParameters CompilerParameters objCompilerParameters = new CompilerParameters(); objCompilerParameters.ReferencedAssemblies.Add("System.dll"); objCompilerParameters.GenerateExecutable = false; objCompilerParameters.GenerateInMemory = true; // 4.CompilerResults CompilerResults cr = provider.CompileAssemblyFromSource(objCompilerParameters, GenerateCode()); if (cr.Errors.HasErrors) { Console.WriteLine("编译错误:"); foreach (CompilerError err in cr.Errors) { Console.WriteLine(err.ErrorText); } } else { // 通过反射,调用HelloWorld的实例 Assembly objAssembly = cr.CompiledAssembly; object objHelloWorld = objAssembly.CreateInstance("DynamicCodeGenerate.HelloWorld"); MethodInfo objMI = objHelloWorld.GetType().GetMethod("OutPut"); Console.WriteLine(objMI.Invoke(objHelloWorld, null)); } Console.ReadLine(); } private static string GenerateCode() { StringBuilder sb = new StringBuilder(); sb.Append("using System;"); sb.Append(Environment.NewLine); sb.Append("namespace DynamicCodeGenerate"); sb.Append(Environment.NewLine); sb.Append("{"); sb.Append(Environment.NewLine); sb.Append(" public class HelloWorld"); sb.Append(Environment.NewLine); sb.Append(" {"); sb.Append(Environment.NewLine); sb.Append(" public string OutPut()"); sb.Append(Environment.NewLine); sb.Append(" {"); sb.Append(Environment.NewLine); sb.Append(" return \"Hello world!\";"); sb.Append(Environment.NewLine); sb.Append(" }"); sb.Append(Environment.NewLine); sb.Append(" }"); sb.Append(Environment.NewLine); sb.Append("}"); string code = sb.ToString(); Console.WriteLine(code); Console.WriteLine(); return code; } } }