如何用C#動態編譯、執行代碼

來源:互聯網
上載者:User

 在開始之前,先熟悉幾個類及部分屬性、方法:CSharpCodeProviderICodeCompilerCompilerParametersCompilerResultsAssembly

  一、CSharpCodeProvider
    提供對C#代碼產生器和代碼編譯器的執行個體的訪問。如果要動態產生VB代碼,可以使用VBCodeProvider

    CreateCompiler():擷取編譯器的執行個體。

  二、ICodeCompiler
    定義用於調用原始碼編譯的介面或使用指定編譯器的CodeDOM樹。每種編譯方法都接受指示編譯器的CompilerParameters對象,並返回指示編譯結果的CompilerResults對象。

    CompilerAssemblyFromSource(CompilerParameters option, string source):使用指定的編譯器,從包含原始碼的字串設定編譯器集。

  三、CompilerParameters
    表示用於調用編譯器的參數。

    ReferencedAssemblies:擷取當前項目所引用的程式集。Add方法為程式集添加引用。
    GenerateExecutable:擷取或設定一個值,該值指示是否產生可執行檔。若此屬性為false,則產生DLL,預設是false。
    GenerateInMemory:擷取或設定一個值,該值指示是否在記憶體中產生輸出。

  四、CompilerResults
    表示從編譯器返回的編譯結果。

    CompiledAssembly:擷取或設定以編譯的程式集,Assembly類型。

  五、Assembly
    就是程式集了(不知道如何描述了)。

  大致瞭解了以上知識之後,就可以使用C#動態編譯並執行代碼了,一下是一段樣本程式:

  1. using System; 
  2. using System.Reflection; 
  3. using System.Globalization; 
  4. using Microsoft.CSharp;
  5. using System.CodeDom; 
  6. using System.CodeDom.Compiler;
  7. using System.Text; 
  8. namespace ConsoleApplication1 
  9. {
  10.     public class Program
  11.     {
  12.         static void Main(string[] args)
  13.         {
  14.             // 1.CSharpCodePrivoder
  15.             CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider();
  16.             // 2.ICodeComplier
  17.             ICodeCompiler objICodeCompiler = objCSharpCodePrivoder.CreateCompiler();
  18.             // 3.CompilerParameters
  19.             CompilerParameters objCompilerParameters = new CompilerParameters();
  20.             objCompilerParameters.ReferencedAssemblies.Add("System.dll");
  21.             objCompilerParameters.GenerateExecutable = false;
  22.             objCompilerParameters.GenerateInMemory = true;
  23.             // 4.CompilerResults
  24.             CompilerResults cr = objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters, GenerateCode());
  25.             if (cr.Errors.HasErrors)
  26.             {
  27.                 Console.WriteLine("編譯錯誤:");
  28.                 foreach (CompilerError err in cr.Errors)
  29.                 {
  30.                     Console.WriteLine(err.ErrorText);
  31.                 }
  32.             }
  33.             else
  34.             {
  35.                 // 通過反射,調用HelloWorld的執行個體
  36.                 Assembly objAssembly = cr.CompiledAssembly;
  37.                 object objHelloWorld = objAssembly.CreateInstance("DynamicCodeGenerate.HelloWorld");
  38.                 MethodInfo objMI = objHelloWorld.GetType().GetMethod("OutPut");
  39.                 Console.WriteLine(objMI.Invoke(objHelloWorld, null));
  40.             }
  41.             Console.ReadLine();
  42.         }
  43.         static string GenerateCode()
  44.         {
  45.             StringBuilder sb = new StringBuilder();
  46.             sb.Append("using System;");
  47.             sb.Append(Environment.NewLine);
  48.             sb.Append("namespace DynamicCodeGenerate");
  49.             sb.Append(Environment.NewLine);
  50.             sb.Append("{");
  51.             sb.Append(Environment.NewLine);
  52.             sb.Append("    public class HelloWorld");
  53.             sb.Append(Environment.NewLine);
  54.             sb.Append("    {");
  55.             sb.Append(Environment.NewLine);
  56.             sb.Append("        public string OutPut()");
  57.             sb.Append(Environment.NewLine);
  58.             sb.Append("        {");
  59.             sb.Append(Environment.NewLine);
  60.             sb.Append("             return \"Hello world!\";");
  61.             sb.Append(Environment.NewLine);
  62.             sb.Append("        }");
  63.             sb.Append(Environment.NewLine);
  64.             sb.Append("    }");
  65.             sb.Append(Environment.NewLine);
  66.             sb.Append("}");
  67.             string code = sb.ToString();
  68.             Console.WriteLine(code);
  69.             Console.WriteLine();
  70.             return code;
  71.         }
  72.     }
  73. }
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.