共用方式為


使用 C# 編譯程式以程式設計方式編譯程式代碼

本文說明如何使用 C# 編譯程式從文字來源編譯程式程式代碼。

原始產品版本: Visual Studio、.NET Framework
原始 KB 編號: 304655

摘要

Microsoft .NET Framework 會公開類別,讓您以程序設計方式存取 C# 語言編譯程式。 如果您想要撰寫自己的程式代碼編譯公用程式,這可能很有用。 本文提供範例程序代碼,可讓您從文字來源編譯程序代碼。 應用程式可讓您只建置可執行檔或建置可執行檔並加以執行。 編譯程式期間發生的任何錯誤都會顯示在窗體上。

需求

  • Visual Studio
  • Visual C# 語言編譯程式

使用 C# 編譯程式編譯程式來編譯程式代碼

.NET Framework 提供 ICodeCompiler 編譯程序執行介面。 類別 CSharpCodeProvider 會實作這個介面,並提供 C# 程式代碼產生器和程式代碼編譯程式的實例存取權。 下列範例程式代碼會建立的 CSharpCodeProvider 實例,並用它來取得介面的 ICodeCompiler 參考。

CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler();

一旦您有介面的 ICodeCompiler 參考,就可以使用它來編譯原始程式碼。 您將使用 CompilerParameters 類別將參數傳遞至編譯程式。 以下是範例:

System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = true;
parameters.OutputAssembly = Output;
CompilerResults results = icc.CompileAssemblyFromSource(parameters,SourceString);

上述程式代碼會 CompilerParameters 使用 對象來告訴編譯程式您想要產生可執行檔(而不是 DLL),而且您想要將產生的元件輸出至磁碟。 的呼叫 CompileAssemblyFromSource 是編譯元件的位置。 這個方法會採用parameters物件和原始程式碼,也就是字串。 編譯程式代碼之後,您可以檢查是否有任何編譯錯誤。 您可以使用 來自 CompileAssemblyFromSource的傳回值,也就是 CompilerResults 物件。 這個物件包含 errors 集合,其中包含編譯期間發生的任何錯誤。

if (results.Errors.Count > 0)
{
    foreach(CompilerError CompErr in results.Errors)
    {
        textBox2.Text = textBox2.Text +
            "Line number " + CompErr.Line +
            ", Error Number: " + CompErr.ErrorNumber +
            ", '" + CompErr.ErrorText + ";" +
            Environment.NewLine + Environment.NewLine;
    }
}

還有其他選項可用來編譯,例如從檔案編譯。 您也可以批次編譯,這表示您可以同時編譯多個檔案或來源。

逐步程式範例

  1. 建立新的 Visual C# .NET Windows 應用程式。 Form1 預設會建立。

  2. 將 Button 控件新增至 Form1,然後將其 Text 屬性變更Build

  3. 將另一個 Button 控件新增至 Form1,然後將其 Text 屬性變更[執行]。

  4. 將兩個 TextBox 控件新增至 Form1、將這兩個控件的 Multiline 屬性設定True,然後調整這些控件的大小,讓您可以將多行文字貼到每一行。

  5. 在程式代碼編輯器中 ,開啟Form1.cs 原始程序檔。

  6. 在類別中 Form1 ,貼上下列按鈕按兩下處理程式。

    private void button1_Click(object sender, System.EventArgs e)
    {
        CSharpCodeProvider codeProvider = new CSharpCodeProvider();
        ICodeCompiler icc = codeProvider.CreateCompiler();
        string Output = "Out.exe";
        Button ButtonObject = (Button)sender;
    
        textBox2.Text = "";
        System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
        //Make sure we generate an EXE, not a DLL
        parameters.GenerateExecutable = true;
        parameters.OutputAssembly = Output;
        CompilerResults results = icc.CompileAssemblyFromSource(parameters, textBox1.Text);
    
        if (results.Errors.Count > 0)
        {
            textBox2.ForeColor = Color.Red;
            foreach (CompilerError CompErr in results.Errors)
            {
                textBox2.Text = textBox2.Text +
                            "Line number " + CompErr.Line +
                            ", Error Number: " + CompErr.ErrorNumber +
                            ", '" + CompErr.ErrorText + ";" +
                            Environment.NewLine + Environment.NewLine;
            }
        }
        else
        {
            //Successful Compile
            textBox2.ForeColor = Color.Blue;
            textBox2.Text = "Success!";
            //If we clicked run then launch our EXE
            if (ButtonObject.Text == "Run") Process.Start(Output);
        }
    }
    

    在檔案的開頭,新增下列 using 語句:

    using System.CodeDom.Compiler;
    using System.Diagnostics;
    using Microsoft.CSharp;
    
  7. Form1.cs 中,找出建構函 Form1 式。

  8. 在建構函式中Form1呼叫 InitializeComponent 之後,將下列程式代碼新增至您新增至 Form1 的兩個按鈕,以連接按鈕按兩擊處理程式。

    public Form1()
    {
        InitializeComponent();
        this.button1.Click += new System.EventHandler(this.button1_Click);
        this.button2.Click += new System.EventHandler(this.button1_Click);
    }
    
  9. 執行專案。 載入 Form1 之後,按兩下 [建置] 按鈕。

    注意

    您會收到編譯程序錯誤。

  10. 接下來,將下列文字複製到文字框中,取代任何現有的文字:

    using System;
    namespace HelloWorld
    {
        /// <summary>
        /// Summary description for Class1.
        /// </summary>
        class HelloWorldClass
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Hello World!");
                Console.ReadLine();
            }
        }
    }
    
  11. 再次按兩下 [ 建置 ]。 編譯應該成功。

  12. 按兩下 [ 執行],它會編譯程式代碼並執行產生的可執行檔。 編譯會建立名為 Out.exe 的可執行檔,該檔案會儲存在您執行的應用程式所在的相同資料夾中。

    注意

    您可以在文字框中修改程式碼,以查看不同的編譯程序錯誤。 例如,刪除其中一個分號並重建程序代碼。

  13. 最後,修改文字框中的程序代碼,將另一行文字輸出至主控台視窗。 按兩下 [ 執行 ] 以查看輸出。

參考資料