C# 動態代碼執行

來源:互聯網
上載者:User
所謂動態代碼執行,和指令碼引擎有點類似。就是程式執行期從字串或者文字檔中讀取一段 C# 代碼,在記憶體中動態編譯成程式集,並建立相互關聯類型執行個體執行相關方法。

具體的實現可參考下面的代碼。如需要產生組件檔,可參考《使用CodeDom產生程式集》。using System;
using System.Reflection;
using System.Globalization;
using Microsoft.CSharp;
using System.CodeDom;
using System.CodeDom.Compiler;

namespace ConsoleApplication1
{
  public class Program
  {
    static void Main(string[] args)
    {
      // 定義需要動態執行的 C# 代碼字串,當然也可從文字檔中讀取。
      string code = @"
        using System;
        namespace MyNamespace
        {
          public class MyClass
          {
            private string name;

            public MyClass(string name)
            {
              this.name = name;
            }

            public void Test()
            {
              Console.WriteLine(""{0} - {1}"", name, DateTime.Now);
            }
          }
        }
      ";

      // 建立編譯器對象
      CSharpCodeProvider p = new CSharpCodeProvider();
      ICodeCompiler cc = p.CreateCompiler();

      // 設定編譯參數
      CompilerParameters options = new CompilerParameters();
      options.ReferencedAssemblies.Add("System.dll");
      options.GenerateInMemory = true;
      options.OutputAssembly = "MyTest";
      
      // 開始編譯
      CodeSnippetCompileUnit cu = new CodeSnippetCompileUnit(code);
      CompilerResults cr = cc.CompileAssemblyFromDom(options, cu);

      // 執行動態程式集相關內容。
      Type t = cr.CompiledAssembly.GetType("MyNamespace.MyClass");
      object o = cr.CompiledAssembly.CreateInstance("MyNamespace.MyClass", false, BindingFlags.Default,
        null, new object[] { "Tom" }, CultureInfo.CurrentCulture, null);
      t.InvokeMember("Test", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod,
        null, o, null);

    }
  }
}0 0

0

(請您對文章做出評價)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.