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代码提供程序编译源文件。 该示例检查输入文件扩展名,并使用相应的 CSharpCodeProviderVBCodeProvider 用于编译。 输入文件编译为可执行文件,任何编译错误都会显示在控制台中。

Important

.NET Core 和 .NET 5+ 上不支持 CompileAssemblyFrom* 方法。 此示例仅在 .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# ICodeGeneratorICodeCompiler 实现实例的方法。

注释

此类在应用于所有成员的类级别包含一个链接请求和一个继承请求。 当直接调用者或派生类没有完全信任权限时,将引起 SecurityException

构造函数

名称 说明
CSharpCodeProvider()

初始化 CSharpCodeProvider 类的新实例。

CSharpCodeProvider(IDictionary<String,String>)

使用指定的提供程序选项初始化类的新实例 CSharpCodeProvider

属性

名称 说明
CanRaiseEvents

获取一个值,该值指示组件是否可以引发事件。

(继承自 Component)
Container

IContainer获取包含 .Component

(继承自 Component)
DesignMode

获取一个值,该值指示当前是否 Component 处于设计模式。

(继承自 Component)
Events

获取附加到此 Component对象的事件处理程序的列表。

(继承自 Component)
FileExtension

获取创建源代码文件时要使用的文件扩展名。

LanguageOptions

获取语言功能标识符。

(继承自 CodeDomProvider)
Site

获取或设置 ISiteComponent

(继承自 Component)

方法

名称 说明
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)

使用指定的选项为指定的代码文档对象模型(CodeDOM)语句生成代码并将其发送到指定的文本编写器。

(继承自 CodeDomProvider)
GenerateCodeFromType(CodeTypeDeclaration, TextWriter, CodeGeneratorOptions)

使用指定的选项为指定的代码文档对象模型(CodeDOM)类型声明生成代码并将其发送到指定的文本编写器。

(继承自 CodeDomProvider)
GetConverter(Type)

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)

活动

名称 说明
Disposed

当组件通过对方法的调用 Dispose() 释放时发生。

(继承自 Component)

适用于

另请参阅