.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!" + "\");" +
                        "}" +
                    "}" +
                "}";
        }
    }


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章