CSharpCodeProvider 类

定义

提供对 C# 代码生成器和代码编译器的实例的访问权限。Provides access to instances of the C# code generator and code compiler.

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 代码提供程序编译源文件。The following example uses either the C# or Visual Basic code provider to compile a source file. 该示例将检查输入文件扩展名,并使用相应CSharpCodeProviderVBCodeProvider或进行编译。The example checks the input file extension and uses the corresponding CSharpCodeProvider or VBCodeProvider for compilation. 输入文件将编译为可执行文件,并且所有编译错误都将显示在控制台中。The input file is compiled into an executable file, and any compilation errors are displayed to the console.

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实现的实例的方法。This class provides methods that can be used to retrieve instances of the C# ICodeGenerator and ICodeCompiler implementations.

备注

此类包含应用于所有成员的类级别的链接要求和继承要求。This class contains a link demand and an inheritance demand at the class level that applies to all members. 当直接调用方或派生类不具有完全信任权限时,将引发。SecurityExceptionA SecurityException is thrown when either the immediate caller or the derived class does not have full-trust permission.

构造函数

CSharpCodeProvider()

初始化 CSharpCodeProvider 类的新实例。Initializes a new instance of the CSharpCodeProvider class.

CSharpCodeProvider(IDictionary<String,String>)

使用指定的提供程序选项初始化 CSharpCodeProvider 类的新实例。Initializes a new instance of the CSharpCodeProvider class by using the specified provider options.

属性

CanRaiseEvents

获取一个指示组件是否可以引发事件的值。Gets a value indicating whether the component can raise an event.

(继承自 Component)
Container

获取 IContainer,它包含 ComponentGets the IContainer that contains the Component.

(继承自 Component)
DesignMode

获取一个值,用以指示 Component 当前是否处于设计模式。Gets a value that indicates whether the Component is currently in design mode.

(继承自 Component)
Events

获取附加到此 Component 的事件处理程序的列表。Gets the list of event handlers that are attached to this Component.

(继承自 Component)
FileExtension

获取要在创建源代码文件时使用的文件扩展名。Gets the file name extension to use when creating source code files.

LanguageOptions

获取语言功能标识符。Gets a language features identifier.

(继承自 CodeDomProvider)
Site

获取或设置 ComponentISiteGets or sets the ISite of the Component.

(继承自 Component)

方法

CompileAssemblyFromDom(CompilerParameters, CodeCompileUnit[])

基于包含在 System.CodeDom 对象的指定数组中的 CodeCompileUnit 树,使用指定的编译器设置编译程序集。Compiles an assembly based on the System.CodeDom trees contained in the specified array of CodeCompileUnit objects, using the specified compiler settings.

(继承自 CodeDomProvider)
CompileAssemblyFromFile(CompilerParameters, String[])

从包含在指定文件中的源代码,使用指定的编译器设置编译程序集。Compiles an assembly from the source code contained in the specified files, using the specified compiler settings.

(继承自 CodeDomProvider)
CompileAssemblyFromSource(CompilerParameters, String[])

从包含源代码的字符串的指定数组,使用指定的编译器设置编译程序集。Compiles an assembly from the specified array of strings containing source code, using the specified compiler settings.

(继承自 CodeDomProvider)
CreateCompiler()

获取 C# 代码编译器的实例。Gets an instance of the C# code compiler.

CreateEscapedIdentifier(String)

创建指定值的转义标识符。Creates an escaped identifier for the specified value.

(继承自 CodeDomProvider)
CreateGenerator()

获取 C# 代码生成器的实例。Gets an instance of the C# code generator.

CreateGenerator(String)

在派生类中重写时,使用指定文件名创建新的代码生成器以用于输出。When overridden in a derived class, creates a new code generator using the specified file name for output.

(继承自 CodeDomProvider)
CreateGenerator(TextWriter)

在派生类中重写时,使用指定的 TextWriter 创建新的代码生成器以用于输出。When overridden in a derived class, creates a new code generator using the specified TextWriter for output.

(继承自 CodeDomProvider)
CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(继承自 MarshalByRefObject)
CreateParser()

在派生类中重写时,创建一个新的代码分析器。When overridden in a derived class, creates a new code parser.

(继承自 CodeDomProvider)
CreateValidIdentifier(String)

为指定的值创建有效标识符。Creates a valid identifier for the specified value.

(继承自 CodeDomProvider)
Dispose()

释放由 Component 使用的所有资源。Releases all resources used by the Component.

(继承自 Component)
Dispose(Boolean)

释放由 Component 占用的非托管资源,还可以另外再释放托管资源。Releases the unmanaged resources used by the Component and optionally releases the managed resources.

(继承自 Component)
Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GenerateCodeFromCompileUnit(CodeCompileUnit, TextWriter, CodeGeneratorOptions)

为指定的代码文档对象模型 (CodeDOM) 编译单元生成代码,并使用指定的选项将代码发送到指定的文本编写器。Generates code for the specified Code Document Object Model (CodeDOM) compilation unit and sends it to the specified text writer, using the specified options.

(继承自 CodeDomProvider)
GenerateCodeFromExpression(CodeExpression, TextWriter, CodeGeneratorOptions)

为指定的代码文档对象模型 (CodeDOM) 表达式生成代码,并使用指定的选项将代码发送到指定的文本编写器。Generates code for the specified Code Document Object Model (CodeDOM) expression and sends it to the specified text writer, using the specified options.

(继承自 CodeDomProvider)
GenerateCodeFromMember(CodeTypeMember, TextWriter, CodeGeneratorOptions)

使用指定的文本编写器和代码生成器选项为指定的类成员生成代码。Generates code for the specified class member using the specified text writer and code generator options.

GenerateCodeFromNamespace(CodeNamespace, TextWriter, CodeGeneratorOptions)

为指定的代码文档对象模型 (CodeDOM) 命名空间生成代码,并使用指定的选项将代码发送到指定的文本编写器。Generates code for the specified Code Document Object Model (CodeDOM) namespace and sends it to the specified text writer, using the specified options.

(继承自 CodeDomProvider)
GenerateCodeFromStatement(CodeStatement, TextWriter, CodeGeneratorOptions)

为指定的代码文档对象模型 (CodeDOM) 语句生成代码,并使用指定的选项将代码发送到指定的文本编写器。Generates code for the specified Code Document Object Model (CodeDOM) statement and sends it to the specified text writer, using the specified options.

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

为指定的代码文档对象模型 (CodeDOM) 类型声明生成代码,并使用指定的选项将代码发送到指定的文本编写器。Generates code for the specified Code Document Object Model (CodeDOM) type declaration and sends it to the specified text writer, using the specified options.

(继承自 CodeDomProvider)
GetConverter(Type)

获取指定对象类型的 TypeConverterGets a TypeConverter for the specified type of object.

GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetLifetimeService()

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(继承自 MarshalByRefObject)
GetService(Type)

返回一个对象,该对象表示由 Component 或它的 Container 提供的服务。Returns an object that represents a service provided by the Component or by its Container.

(继承自 Component)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
GetTypeOutput(CodeTypeReference)

获取由指定的 CodeTypeReference 指示的类型。Gets the type indicated by the specified CodeTypeReference.

(继承自 CodeDomProvider)
InitializeLifetimeService()

获取生存期服务对象来控制此实例的生存期策略。Obtains a lifetime service object to control the lifetime policy for this instance.

(继承自 MarshalByRefObject)
IsValidIdentifier(String)

返回一个值,该值指示指定的值是否是当前语言的有效标识符。Returns a value that indicates whether the specified value is a valid identifier for the current language.

(继承自 CodeDomProvider)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。Creates a shallow copy of the current MarshalByRefObject object.

(继承自 MarshalByRefObject)
Parse(TextReader)

将从指定文本流读取的代码编译进 CodeCompileUnitCompiles the code read from the specified text stream into a CodeCompileUnit.

(继承自 CodeDomProvider)
Supports(GeneratorSupport)

返回一个值,该值指示是否提供了指定的代码生成支持。Returns a value indicating whether the specified code generation support is provided.

(继承自 CodeDomProvider)
ToString()

返回包含 Component 的名称的 String(如果有)。Returns a String containing the name of the Component, if any. 不应重写此方法。This method should not be overridden.

(继承自 Component)

事件

Disposed

当通过调用 Dispose() 方法释放组件时发生。Occurs when the component is disposed by a call to the Dispose() method.

(继承自 Component)

安全性

LinkDemand
完全信任直接调用方。for full trust for the immediate caller. 此类不能由部分信任的代码使用。This class cannot be used by partially trusted code.

InheritanceDemand
完全信任继承者。for full trust for inheritors. 此类不能由部分信任的代码继承。This class cannot be inherited by partially trusted code.

适用于

另请参阅