.NET动态编译

前段时间朋友问我.NET有没有一种动态编译字符串的方式,遂写了个Demo 如下:

using System;
#region Using Compiler
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
#endregion
namespace Ahoo.Demo.DynamicCompiler
{
    class Program
    {
        static void Main(string[] args)
        {
            CSharpCodeProvider csCoderPro = new CSharpCodeProvider();
            CompilerParameters comParams = new CompilerParameters();
            comParams.ReferencedAssemblies.Add("System.dll");
            comParams.GenerateExecutable = false;
            comParams.GenerateInMemory = true;

            CompilerResults comResult = csCoderPro.CompileAssemblyFromSource(comParams, GetCode());
            if (comResult.Errors.HasErrors)
            {
                Console.WriteLine("编译异常!");
                return;
            }
            Assembly objAssembly = comResult.CompiledAssembly;
            object objHW = objAssembly.CreateInstance("Ahoo.Demo.DynamicCompiler.HelloWorld");
            MethodInfo objMI = objHW.GetType().GetMethod("Hello");

            objMI.Invoke(objHW, null);

            Console.ReadLine();
        }

        public static String GetCode()
        {
            return
                "using System;" +
                "namespace Ahoo.Demo.DynamicCompiler" +
                "{" +
                    "public class HelloWorld" +
                    "{" +
                        "public void Hello()" +
                        "{" +
                            "Console.WriteLine(\"" + "Hello World!" + "\");" +
                        "}" +
                    "}" +
                "}";
        }
    }


}

你可能感兴趣的:(.NET动态编译)