CSharpCodeProvider 類別

定義

提供 C# 程式碼產生器與程式碼編譯器的實例存取。

public ref class CSharpCodeProvider : System::CodeDom::Compiler::CodeDomProvider
public class CSharpCodeProvider : System.CodeDom.Compiler.CodeDomProvider
type CSharpCodeProvider = class
    inherit CodeDomProvider
Public Class CSharpCodeProvider
Inherits CodeDomProvider
繼承

範例

以下範例使用 C# 或 Visual Basic 程式碼提供者來編譯原始碼檔案。 範例中檢查輸入檔案副檔名,並使用對應 CSharpCodeProvider 的 or VBCodeProvider 來編譯。 輸入檔案會被編譯成可執行檔,任何編譯錯誤會顯示給主控台。

Important

CompileAssemblyFrom* 方法在 .NET Core 和 .NET 5+ 上不被支援。 這個範例僅能在 .NET Framework 上執行。

using System;
using System.IO;
using System.Globalization;
using System.CodeDom.Compiler;
using System.Text;
using Microsoft.CSharp;
using Microsoft.VisualBasic;

namespace CodeProviders
{
    class CompileSample
    {
        [STAThread]
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                //  First parameter is the source file name.
                if (File.Exists(args[0]))
                {
                    CompileExecutable(args[0]);
                }
                else
                {
                    Console.WriteLine("Input source file not found - {0}",
                        args[0]);
                }
            }
            else
            {
                Console.WriteLine("Input source file not specified on command line!");
            }
        }

        public static bool CompileExecutable(String sourceName)
        {
            FileInfo sourceFile = new FileInfo(sourceName);
            CodeDomProvider provider = null;
            bool compileOk = false;

            // Select the code provider based on the input file extension.
            if (sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) == ".CS")
            {
                provider = CodeDomProvider.CreateProvider("CSharp");
            }
            else if (sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) == ".VB")
            {
                provider = CodeDomProvider.CreateProvider("VisualBasic");
            }
            else
            {
                Console.WriteLine("Source file must have a .cs or .vb extension");
            }

            if (provider != null)
            {

                // Format the executable file name.
                // Build the output assembly path using the current directory
                // and <source>_cs.exe or <source>_vb.exe.

                String exeName = String.Format(@"{0}\{1}.exe",
                    System.Environment.CurrentDirectory,
                    sourceFile.Name.Replace(".", "_"));

                CompilerParameters cp = new CompilerParameters();

                // Generate an executable instead of
                // a class library.
                cp.GenerateExecutable = true;

                // Specify the assembly file name to generate.
                cp.OutputAssembly = exeName;

                // Save the assembly as a physical file.
                cp.GenerateInMemory = false;

                // Set whether to treat all warnings as errors.
                cp.TreatWarningsAsErrors = false;

                // Invoke compilation of the source file.
                CompilerResults cr = provider.CompileAssemblyFromFile(cp,
                    sourceName);

                if(cr.Errors.Count > 0)
                {
                    // Display compilation errors.
                    Console.WriteLine("Errors building {0} into {1}",
                        sourceName, cr.PathToAssembly);
                    foreach(CompilerError ce in cr.Errors)
                    {
                        Console.WriteLine("  {0}", ce.ToString());
                        Console.WriteLine();
                    }
                }
                else
                {
                    // Display a successful compilation message.
                    Console.WriteLine("Source {0} built into {1} successfully.",
                        sourceName, cr.PathToAssembly);
                }

                // Return the results of the compilation.
                if (cr.Errors.Count > 0)
                {
                    compileOk = false;
                }
                else
                {
                    compileOk = true;
                }
            }
            return compileOk;
        }
    }
}
Imports System.IO
Imports System.Globalization
Imports System.CodeDom.Compiler
Imports System.Text
Imports Microsoft.CSharp

Namespace CodeProviders
    Class CompileSample
        <STAThread()>  _
        Public Shared Sub Main(args() As String)

            If args.Length > 0
                ' First parameter is the source file name.
                If File.Exists(args(0))
                    CompileExecutable(args(0))
                Else 
                    Console.WriteLine("Input source file not found - {0}", _
                        args(0))
                End If
            
            Else
                Console.WriteLine("Input source file not specified on command line!")
            End If
        End Sub

        Public Shared Function CompileExecutable(sourceName As String) As Boolean
            Dim sourceFile As FileInfo = New FileInfo(sourceName)
            Dim provider As CodeDomProvider = Nothing
            Dim compileOk As Boolean = False

            ' Select the code provider based on the input file extension.
            If sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) = ".CS"

                provider = CodeDomProvider.CreateProvider("CSharp")

            ElseIf sourceFile.Extension.ToUpper(CultureInfo.InvariantCulture) = ".VB"

                provider = CodeDomProvider.CreateProvider("VisualBasic")

            Else
                Console.WriteLine("Source file must have a .cs or .vb extension")
            End If

            If Not provider Is Nothing

                ' Format the executable file name.
                ' Build the output assembly path using the current directory
                ' and <source>_cs.exe or <source>_vb.exe.

                Dim exeName As String = String.Format("{0}\{1}.exe", _
                    System.Environment.CurrentDirectory, _
                    sourceFile.Name.Replace(".", "_"))

                Dim cp As CompilerParameters = new CompilerParameters()

                ' Generate an executable instead of 
                ' a class library.
                cp.GenerateExecutable = True

                ' Specify the assembly file name to generate.
                cp.OutputAssembly = exeName
    
                ' Save the assembly as a physical file.
                cp.GenerateInMemory = False
    
                ' Set whether to treat all warnings as errors.
                cp.TreatWarningsAsErrors = False
 
                ' Invoke compilation of the source file.
                Dim cr As CompilerResults = provider.CompileAssemblyFromFile(cp, _
                    sourceName)
    
                If cr.Errors.Count > 0
                    ' Display compilation errors.
                    Console.WriteLine("Errors building {0} into {1}", _
                        sourceName, cr.PathToAssembly)

                    Dim ce As CompilerError
                    For Each ce In cr.Errors
                        Console.WriteLine("  {0}", ce.ToString())
                        Console.WriteLine()
                    Next ce
                Else
                    ' Display a successful compilation message.
                    Console.WriteLine("Source {0} built into {1} successfully.", _
                        sourceName, cr.PathToAssembly)
                End If
              
                ' Return the results of the compilation.
                If cr.Errors.Count > 0
                    compileOk = False
                Else 
                    compileOk = True
                End If
            End If
            return compileOk

        End Function
    End Class
End Namespace

備註

此類別提供可用於檢索 C# ICodeGenerator 實例及其 ICodeCompiler 實作的方法。

Note

這個類別包含適用於所有成員之類別層級的連結需求和繼承需求。 當立即呼叫者或衍生類別沒有完全信任權限時,會拋出SecurityException

建構函式

名稱 Description
CSharpCodeProvider()

初始化 CSharpCodeProvider 類別的新執行個體。

CSharpCodeProvider(IDictionary<String,String>)

透過使用指定的提供者選項初始化該類別的新 CSharpCodeProvider 實例。

屬性

名稱 Description
CanRaiseEvents

會得到一個值,表示該元件是否能引發事件。

(繼承來源 Component)
Container

得到 IContainer 包含 Component的 。

(繼承來源 Component)
DesignMode

會得到一個值,表示目前 Component 是否處於設計模式。

(繼承來源 Component)
Events

會取得與此 Component連結的事件處理程序清單。

(繼承來源 Component)
FileExtension

取得檔案副檔名,用於建立原始碼檔案。

LanguageOptions

取得語言特徵識別碼。

(繼承來源 CodeDomProvider)
Site

取得或設定 ISiteComponent

(繼承來源 Component)

方法

名稱 Description
CompileAssemblyFromDom(CompilerParameters, CodeCompileUnit[])

根據指定物件陣列System.CodeDom中包含的樹狀結構,使用指定的編譯器設定編譯組合語言CodeCompileUnit

(繼承來源 CodeDomProvider)
CompileAssemblyFromFile(CompilerParameters, String[])

根據指定檔案中的原始碼,使用指定的編譯器設定,編譯組合語言。

(繼承來源 CodeDomProvider)
CompileAssemblyFromSource(CompilerParameters, String[])

從指定的字串陣列編譯組譯,並使用指定的編譯器設定。

(繼承來源 CodeDomProvider)
CreateCompiler()
已淘汰.

取得 C# 程式碼編譯器的實例。

CreateEscapedIdentifier(String)

為指定值建立一個逃逸識別碼。

(繼承來源 CodeDomProvider)
CreateGenerator()
已淘汰.

取得一個 C# 程式碼產生器的實例。

CreateGenerator(String)

當在派生類別中覆寫時,會建立一個新的程式碼產生器,使用指定的檔案名稱作為輸出。

(繼承來源 CodeDomProvider)
CreateGenerator(TextWriter)

當在衍生類別中覆寫時,會根據指定的 TextWriter 輸出產生器建立新的程式碼產生器。

(繼承來源 CodeDomProvider)
CreateObjRef(Type)

建立一個物件,包含產生代理伺服器所需的所有相關資訊,用於與遠端物件通訊。

(繼承來源 MarshalByRefObject)
CreateParser()
已淘汰.

當在衍生類別中覆寫時,會產生新的程式碼解析器。

(繼承來源 CodeDomProvider)
CreateValidIdentifier(String)

為指定值建立有效的識別碼。

(繼承來源 CodeDomProvider)
Dispose()

釋放所有由 Component.

(繼承來源 Component)
Dispose(Boolean)

釋放 未管理的資源, Component 並可選擇性地釋放受管理資源。

(繼承來源 Component)
Equals(Object)

判斷指定的 物件是否等於目前的物件。

(繼承來源 Object)
GenerateCodeFromCompileUnit(CodeCompileUnit, TextWriter, CodeGeneratorOptions)

為指定的程式碼文件物件模型(CodeDOM)編譯單元產生程式碼,並依照指定選項傳送給指定的文字寫入器。

(繼承來源 CodeDomProvider)
GenerateCodeFromExpression(CodeExpression, TextWriter, CodeGeneratorOptions)

產生指定的程式碼文件物件模型(CodeDOM)表達式程式碼,並依照指定選項傳送給指定的文字撰寫器。

(繼承來源 CodeDomProvider)
GenerateCodeFromMember(CodeTypeMember, TextWriter, CodeGeneratorOptions)

利用指定的文字寫入器與程式碼產生器選項,為指定的類別成員產生程式碼。

GenerateCodeFromNamespace(CodeNamespace, TextWriter, CodeGeneratorOptions)

為指定的程式碼文件物件模型(CodeDOM)命名空間產生程式碼,並依照指定選項傳送給指定的文字撰寫器。

(繼承來源 CodeDomProvider)
GenerateCodeFromStatement(CodeStatement, TextWriter, CodeGeneratorOptions)

為指定的程式碼文件物件模型(Code Document Object Model,CodeDOM)語句產生程式碼,並透過指定的選項傳送給指定的文字撰寫者。

(繼承來源 CodeDomProvider)
GenerateCodeFromType(CodeTypeDeclaration, TextWriter, CodeGeneratorOptions)

產生指定的程式碼文件物件模型(Code Document Object Model,CodeDOM)宣告程式碼,並透過指定的選項傳送給指定的文字撰寫者。

(繼承來源 CodeDomProvider)
GetConverter(Type)

會獲得指定物件類型的 a TypeConverter

GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetLifetimeService()

取得目前控制此實例生命週期政策的終身服務物件。

(繼承來源 MarshalByRefObject)
GetService(Type)

回傳一個由 或Component其 所提供的Container服務的物件。

(繼承來源 Component)
GetType()

取得目前實例的 Type

(繼承來源 Object)
GetTypeOutput(CodeTypeReference)

得到由指定 CodeTypeReference所指示的類型。

(繼承來源 CodeDomProvider)
InitializeLifetimeService()

取得一個終身服務物件以控制此實例的終身政策。

(繼承來源 MarshalByRefObject)
IsValidIdentifier(String)

回傳一個值,指示該指定值是否為當前語言的有效識別碼。

(繼承來源 CodeDomProvider)
MemberwiseClone()

建立目前 Object的淺層複本。

(繼承來源 Object)
MemberwiseClone(Boolean)

建立一個 MarshalByRefObject 目前物件的淺層複製品。

(繼承來源 MarshalByRefObject)
Parse(TextReader)

將從指定文字串流讀取的程式碼編譯成 CodeCompileUnit

(繼承來源 CodeDomProvider)
Supports(GeneratorSupport)

回傳一個值,表示是否提供指定的程式碼產生支援。

(繼承來源 CodeDomProvider)
ToString()

回傳 String 包含 的名稱 Component(若有的話)。 此方法不應被覆蓋。

(繼承來源 Component)

事件

名稱 Description
Disposed

當元件被呼叫方法 Dispose() 時會發生。

(繼承來源 Component)

適用於

另請參閱