文章編號: 304655 - 上次校閱: 2008年7月30日 - 版次: 3.1

如何以程式設計方式使用 C# 編譯器的編譯程式碼

系統提示本文適用於您使用的作業系統之外的作業系統。與您不相關的文章內容已停用。
本文章的有 Visual Basic.NET] 版本請參閱 304654? (http://support.microsoft.com/kb/304654/ )

在此頁中

全部展開 | 全部摺疊

結論

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

其他相關資訊

步驟 1: 需求

  • Visual Studio
  • Visual C# 語言編譯器

步驟 2: 如何以程式設計方式編譯的程式碼

.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 呼叫是組件取得編譯。 這個方法會採用參數物件和來源程式碼是一個字串。 編譯您的程式碼之後您可以檢查是否發生了任何編譯錯誤,請參閱。 您使用來自 CompileAssemblyFromSource,這是一個 CompilerResults 物件傳回的值。 這個物件包含包含編譯期間發生任何錯誤的一個錯誤] 集合。
   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;
    }
   }
				

有其他選項可用來編譯例如從一個檔案編譯。 您也可以批次編譯這表示您可以在同一時間編譯多個檔案或來源。 您可以 MSDN 線上程式庫中找到這些類別的其他資訊:
http://msdn.microsoft.com/en-us/default.aspx (http://msdn.microsoft.com/en-us/default.aspx)

步驟 3: Step-by-Step 程序範例

  1. 建立新的 Visual C#.NET Windows 應用程式。 預設會建立 Form1。
  2. 按鈕 控制項加入至 Form1,並變更其 Text 屬性來 建置
  3. 將另一個的 按鈕 控制項加入至 Form1,然後將其 Text 屬性變更為 執行
  4. 將兩個 文字方塊 控制項加入至 Form1、 將這兩個控制項該 多行的屬性 設定為 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);
        }
    }
    Add the beginning of the file, add these using statements:
    using System.CodeDom.Compiler;
    using System.Diagnostics;
    using Microsoft.CSharp;
    
    附註 如果您使用 Visual Studio 2005 或 Visual 的 Studio 2008 CSharpCodeProvider 類別已被取代。您可以改用 CodeDomProvider 類別,如下列 button1_Click 實作示範。
    private void button1_Click(object sender, System.EventArgs e)
    {
        CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
        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 = codeProvider.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);
        }
    }
    Add the beginning of the file, add these using statements:
    using System.CodeDom.Compiler;
    using System.Diagnostics;
    
  7. 在 [Form1.cs],尋找 Form1 的建構函式。
  8. 呼叫 InitializeComponent Form1 建構函式中的加入之後下列程式碼,以電傳按鈕按一下您新增到 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. 最後,修改程式碼,在文字方塊中要輸出至主控台視窗的文字另一列。 按一下 [執行] 請參閱輸出。

?考

CSharpCodeProvider 類別
http://msdn.microsoft.com/en-us/library/microsoft.csharp.csharpcodeprovider.aspx (http://msdn.microsoft.com/en-us/library/microsoft.csharp.csharpcodeprovider.aspx)

ICodeCompiler 介面
http://msdn.microsoft.com/en-us/library/system.codedom.compiler.icodecompiler.aspx (http://msdn.microsoft.com/en-us/library/system.codedom.compiler.icodecompiler.aspx)

這篇文章中的資訊適用於:
  • Microsoft Visual C# 2008 Express Edition
  • Microsoft .NET Framework 1.0?應用於:
    • Microsoft Visual C# .NET 2002 Standard Edition
關鍵字:?
kbmt kbsweptvs2008 kbbcl kbcompiler kbhowto kbprod2web KB304655 KbMtzh
機器翻譯機器翻譯
重要:本文是以 Microsoft 機器翻譯軟體翻譯而成,而非使用人工翻譯而成。Microsoft 同時提供使用者人工翻譯及機器翻譯兩個版本的文章,讓使用者可以依其使用語言使用知識庫中的所有文章。但是,機器翻譯的文章可能不盡完美。這些文章中也可能出現拼字、語意或文法上的錯誤,就像外國人在使用本國語言時可能發生的錯誤。Microsoft 不為內容的翻譯錯誤或客戶對該內容的使用所產生的任何錯誤或損害負責。Microsoft也同時將不斷地就機器翻譯軟體進行更新。
按一下這裡查看此文章的英文版本:304655? (http://support.microsoft.com/kb/304655/en-us/ )
Microsoft及(或)其供應商不就任何在本伺服器上發表的文字資料及其相關圖表資訊的恰當性作任何承諾。所有文字資料及其相關圖表均以「現狀」供應,不負任何擔保責任。Microsoft及(或)其供應商謹此聲明,不負任何對與此資訊有關之擔保責任,包括關於適售性、適用於某一特定用途、權利或不侵權的明示或默示擔保責任。Microsoft及(或)其供應商無論如何不對因或與使用本伺服器上資訊或與資訊的實行有關而引起的契約、過失或其他侵權行為之訴訟中的特別的、間接的、衍生性的損害或任何因使用而喪失所導致的之損害、資料或利潤負任何責任。