CompilerParameters Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Representa os parâmetros usados para invocar um compilador.
public ref class CompilerParameters
[System.Runtime.InteropServices.ComVisible(false)]
public class CompilerParameters
[System.Serializable]
public class CompilerParameters
[<System.Runtime.InteropServices.ComVisible(false)>]
type CompilerParameters = class
[<System.Serializable>]
type CompilerParameters = class
Public Class CompilerParameters
- Herança
-
CompilerParameters
- Derivado
- Atributos
Exemplos
O exemplo seguinte constrói um grafo-fonte CodeDOM para um programa simples do Hello World. A fonte é então guardada num ficheiro, compilada num executável e executada. O CompileCode método ilustra como usar a CompilerParameters classe para especificar várias definições e opções do compilador.
using System;
using System.Globalization;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Diagnostics;
namespace CompilerParametersExample
{
class CompileClass
{
// Build a Hello World program graph using System.CodeDom types.
public static CodeCompileUnit BuildHelloWorldGraph()
{
// Create a new CodeCompileUnit to contain the program graph
CodeCompileUnit compileUnit = new CodeCompileUnit();
// Declare a new namespace called Samples.
CodeNamespace samples = new CodeNamespace("Samples");
// Add the new namespace to the compile unit.
compileUnit.Namespaces.Add( samples );
// Add the new namespace import for the System namespace.
samples.Imports.Add( new CodeNamespaceImport("System") );
// Declare a new type called Class1.
CodeTypeDeclaration class1 = new CodeTypeDeclaration("Class1");
// Add the new type to the namespace's type collection.
samples.Types.Add(class1);
// Declare a new code entry point method.
CodeEntryPointMethod start = new CodeEntryPointMethod();
// Create a type reference for the System.Console class.
CodeTypeReferenceExpression csSystemConsoleType = new CodeTypeReferenceExpression("System.Console");
// Build a Console.WriteLine statement.
CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression(
csSystemConsoleType, "WriteLine",
new CodePrimitiveExpression("Hello World!") );
// Add the WriteLine call to the statement collection.
start.Statements.Add(cs1);
// Build another Console.WriteLine statement.
CodeMethodInvokeExpression cs2 = new CodeMethodInvokeExpression(
csSystemConsoleType, "WriteLine",
new CodePrimitiveExpression("Press the Enter key to continue.") );
// Add the WriteLine call to the statement collection.
start.Statements.Add(cs2);
// Build a call to System.Console.ReadLine.
CodeMethodInvokeExpression csReadLine = new CodeMethodInvokeExpression(
csSystemConsoleType, "ReadLine");
// Add the ReadLine statement.
start.Statements.Add(csReadLine);
// Add the code entry point method to the Members
// collection of the type.
class1.Members.Add( start );
return compileUnit;
}
public static String GenerateCode(CodeDomProvider provider,
CodeCompileUnit compileunit)
{
// Build the source file name with the language
// extension (vb, cs, js).
String sourceFile;
if (provider.FileExtension[0] == '.')
{
sourceFile = "HelloWorld" + provider.FileExtension;
}
else
{
sourceFile = "HelloWorld." + provider.FileExtension;
}
// Create a TextWriter to a StreamWriter to an output file.
IndentedTextWriter tw = new IndentedTextWriter(new StreamWriter(sourceFile, false), " ");
// Generate source code using the code provider.
provider.GenerateCodeFromCompileUnit(compileunit, tw, new CodeGeneratorOptions());
// Close the output file.
tw.Close();
return sourceFile;
}
public static bool CompileCode(CodeDomProvider provider,
String sourceFile,
String exeFile)
{
CompilerParameters cp = new CompilerParameters();
// Generate an executable instead of
// a class library.
cp.GenerateExecutable = true;
// Set the assembly file name to generate.
cp.OutputAssembly = exeFile;
// Generate debug information.
cp.IncludeDebugInformation = true;
// Add an assembly reference.
cp.ReferencedAssemblies.Add( "System.dll" );
// Save the assembly as a physical file.
cp.GenerateInMemory = false;
// Set the level at which the compiler
// should start displaying warnings.
cp.WarningLevel = 3;
// Set whether to treat all warnings as errors.
cp.TreatWarningsAsErrors = false;
// Set compiler argument to optimize output.
cp.CompilerOptions = "/optimize";
// Set a temporary files collection.
// The TempFileCollection stores the temporary files
// generated during a build in the current directory,
// and does not delete them after compilation.
cp.TempFiles = new TempFileCollection(".", true);
if (provider.Supports(GeneratorSupport.EntryPointMethod))
{
// Specify the class that contains
// the main method of the executable.
cp.MainClass = "Samples.Class1";
}
if (Directory.Exists("Resources"))
{
if (provider.Supports(GeneratorSupport.Resources))
{
// Set the embedded resource file of the assembly.
// This is useful for culture-neutral resources,
// or default (fallback) resources.
cp.EmbeddedResources.Add("Resources\\Default.resources");
// Set the linked resource reference files of the assembly.
// These resources are included in separate assembly files,
// typically localized for a specific language and culture.
cp.LinkedResources.Add("Resources\\nb-no.resources");
}
}
// Invoke compilation.
CompilerResults cr = provider.CompileAssemblyFromFile(cp, sourceFile);
if(cr.Errors.Count > 0)
{
// Display compilation errors.
Console.WriteLine("Errors building {0} into {1}",
sourceFile, cr.PathToAssembly);
foreach(CompilerError ce in cr.Errors)
{
Console.WriteLine(" {0}", ce.ToString());
Console.WriteLine();
}
}
else
{
Console.WriteLine("Source {0} built into {1} successfully.",
sourceFile, cr.PathToAssembly);
Console.WriteLine("{0} temporary files created during the compilation.",
cp.TempFiles.Count.ToString());
}
// Return the results of compilation.
if (cr.Errors.Count > 0)
{
return false;
}
else
{
return true;
}
}
[STAThread]
static void Main()
{
CodeDomProvider provider = null;
String exeName = "HelloWorld.exe";
Console.WriteLine("Enter the source language for Hello World (cs, vb, etc):");
String inputLang = Console.ReadLine();
Console.WriteLine();
if (CodeDomProvider.IsDefinedLanguage(inputLang))
{
provider = CodeDomProvider.CreateProvider(inputLang);
}
if (provider == null)
{
Console.WriteLine("There is no CodeDomProvider for the input language.");
}
else
{
CodeCompileUnit helloWorld = BuildHelloWorldGraph();
String sourceFile = GenerateCode(provider, helloWorld);
Console.WriteLine("HelloWorld source code generated.");
if (CompileCode(provider, sourceFile, exeName ))
{
Console.WriteLine("Starting HelloWorld executable.");
Process.Start(exeName);
}
}
}
}
}
Imports System.Globalization
Imports System.CodeDom
Imports System.CodeDom.Compiler
Imports System.Collections
Imports System.ComponentModel
Imports System.IO
Imports System.Diagnostics
Namespace CompilerParametersExample
Class CompileClass
' Build a Hello World program graph using System.CodeDom types.
Public Shared Function BuildHelloWorldGraph() As CodeCompileUnit
' Create a new CodeCompileUnit to contain the program graph.
Dim compileUnit As New CodeCompileUnit()
' Declare a new namespace called Samples.
Dim samples As New CodeNamespace("Samples")
' Add the new namespace to the compile unit.
compileUnit.Namespaces.Add(samples)
' Add the new namespace import for the System namespace.
samples.Imports.Add(New CodeNamespaceImport("System"))
' Declare a new type called Class1.
Dim Class1 As New CodeTypeDeclaration("Class1")
' Add the new type to the namespace's type collection.
samples.Types.Add(class1)
' Declare a new code entry point method
Dim start As New CodeEntryPointMethod()
' Create a type reference for the System.Console class.
Dim csSystemConsoleType As New CodeTypeReferenceExpression( _
"System.Console")
' Build a Console.WriteLine statement.
Dim cs1 As New CodeMethodInvokeExpression( _
csSystemConsoleType, "WriteLine", _
New CodePrimitiveExpression("Hello World!"))
' Add the WriteLine call to the statement collection.
start.Statements.Add(cs1)
' Build another Console.WriteLine statement.
Dim cs2 As New CodeMethodInvokeExpression( _
csSystemConsoleType, "WriteLine", _
New CodePrimitiveExpression("Press the Enter key to continue."))
' Add the WriteLine call to the statement collection.
start.Statements.Add(cs2)
' Build a call to System.Console.ReadLine.
Dim csReadLine As New CodeMethodInvokeExpression( _
csSystemConsoleType, "ReadLine")
' Add the ReadLine statement.
start.Statements.Add(csReadLine)
' Add the code entry point method to the Members
' collection of the type.
class1.Members.Add(start)
Return compileUnit
End Function
Public Shared Function GenerateCode(ByVal provider As CodeDomProvider, _
ByVal compileunit As CodeCompileUnit) As String
' Build the source file name with the language extension (vb, cs, js).
Dim sourceFile As String
If provider.FileExtension.StartsWith(".") Then
sourceFile = "HelloWorld" + provider.FileExtension
Else
sourceFile = "HelloWorld." + provider.FileExtension
End If
' Create a TextWriter to a StreamWriter to an output file.
Dim tw As New IndentedTextWriter(New StreamWriter(sourceFile, False), " ")
' Generate source code using the code provider.
provider.GenerateCodeFromCompileUnit(compileunit, tw, _
New CodeGeneratorOptions())
' Close the output file.
tw.Close()
Return sourceFile
End Function 'GenerateCode
Public Shared Function CompileCode(ByVal provider As CodeDomProvider, _
ByVal sourceFile As String, ByVal exeFile As String) As Boolean
Dim cp As New CompilerParameters()
' Generate an executable instead of
' a class library.
cp.GenerateExecutable = True
' Set the assembly file name to generate.
cp.OutputAssembly = exeFile
' Generate debug information.
cp.IncludeDebugInformation = True
' Add an assembly reference.
cp.ReferencedAssemblies.Add("System.dll")
' Save the assembly as a physical file.
cp.GenerateInMemory = False
' Set the level at which the compiler
' should start displaying warnings.
cp.WarningLevel = 3
' Set whether to treat all warnings as errors.
cp.TreatWarningsAsErrors = False
' Set compiler argument to optimize output.
cp.CompilerOptions = "/optimize"
' Set a temporary files collection.
' The TempFileCollection stores the temporary files
' generated during a build in the current directory,
' and does not delete them after compilation.
cp.TempFiles = New TempFileCollection(".", True)
If provider.Supports(GeneratorSupport.EntryPointMethod) Then
' Specify the class that contains
' the main method of the executable.
cp.MainClass = "Samples.Class1"
End If
If Directory.Exists("Resources") Then
If provider.Supports(GeneratorSupport.Resources) Then
' Set the embedded resource file of the assembly.
' This is useful for culture-neutral resources,
' or default (fallback) resources.
cp.EmbeddedResources.Add("Resources\Default.resources")
' Set the linked resource reference files of the assembly.
' These resources are included in separate assembly files,
' typically localized for a specific language and culture.
cp.LinkedResources.Add("Resources\nb-no.resources")
End If
End If
' Invoke compilation.
Dim cr As CompilerResults = _
provider.CompileAssemblyFromFile(cp, sourceFile)
If cr.Errors.Count > 0 Then
' Display compilation errors.
Console.WriteLine("Errors building {0} into {1}", _
sourceFile, cr.PathToAssembly)
Dim ce As CompilerError
For Each ce In cr.Errors
Console.WriteLine(" {0}", ce.ToString())
Console.WriteLine()
Next ce
Else
Console.WriteLine("Source {0} built into {1} successfully.", _
sourceFile, cr.PathToAssembly)
Console.WriteLine("{0} temporary files created during the compilation.", _
cp.TempFiles.Count.ToString())
End If
' Return the results of compilation.
If cr.Errors.Count > 0 Then
Return False
Else
Return True
End If
End Function 'CompileCode
<STAThread()> _
Shared Sub Main()
Dim exeName As String = "HelloWorld.exe"
Dim provider As CodeDomProvider = Nothing
Console.WriteLine("Enter the source language for Hello World (cs, vb, etc):")
Dim inputLang As String = Console.ReadLine()
Console.WriteLine()
If CodeDomProvider.IsDefinedLanguage(inputLang) Then
Dim helloWorld As CodeCompileUnit = BuildHelloWorldGraph()
provider = CodeDomProvider.CreateProvider(inputLang)
Dim sourceFile As String
sourceFile = GenerateCode(provider, helloWorld)
Console.WriteLine("HelloWorld source code generated.")
If CompileCode(provider, sourceFile, exeName) Then
Console.WriteLine("Starting HelloWorld executable.")
Process.Start(exeName)
End If
End If
If provider Is Nothing Then
Console.WriteLine("There is no CodeDomProvider for the input language.")
End If
End Sub
End Class
End Namespace
Observações
Um CompilerParameters objeto representa as definições e opções para uma ICodeCompiler interface.
Se você estiver compilando um programa executável, você deve definir a GenerateExecutable propriedade como true. Quando o GenerateExecutable estiver definido como false, o compilador gerará uma biblioteca de classes. Por padrão, um novo CompilerParameters é inicializado com sua GenerateExecutable propriedade definida como false. Se você estiver compilando um executável a partir de um gráfico CodeDOM, um CodeEntryPointMethod deve ser definido no gráfico. Se existirem múltiplos pontos de entrada de código, pode indicar a classe que define o ponto de entrada a usar, definindo o nome da classe para a MainClass propriedade.
Pode especificar um nome de ficheiro para o conjunto de saída na OutputAssembly propriedade. Caso contrário, um nome de arquivo de saída padrão será usado. Para incluir informação de depuração numa assembly gerada, defina a IncludeDebugInformation propriedade para true. Se o seu projeto referenciar algum assembly, deve especificar os nomes de assembly como itens num StringCollection conjunto à ReferencedAssemblies propriedade do CompilerParameters usado ao invocar a compilação.
Você pode compilar um assembly que é gravado na memória em vez de no disco definindo a propriedade GenerateInMemory para true. Quando um assembly é gerado na memória, o seu código pode obter uma referência ao assembly gerado da propriedade de CompiledAssembly. Se um assembly for gravado no disco, poderá obter o caminho para o assembly gerado da propriedade de um PathToAssembly.
Para especificar um nível de aviso no qual interromper a compilação, defina a WarningLevel propriedade como um inteiro que representa o nível de aviso no qual a compilação deve ser interrompida. Você também pode configurar o compilador para interromper a compilação se forem encontrados avisos definindo a TreatWarningsAsErrors propriedade como true.
Para especificar argumentos de linha de comando personalizados a serem usados ao invocar o processo de compilação, defina o valor da propriedade para CompilerOptions. Se um token de segurança Win32 for necessário para invocar o processo do compilador, especifique o token UserToken na propriedade. Para incluir .NET ficheiros de recurso do Framework na assembly compilada, adicione os nomes dos ficheiros de recurso à propriedade EmbeddedResources. Para referenciar .NET recursos do Framework noutra assembleia, adicione os nomes dos ficheiros de recursos à propriedade LinkedResources. Para incluir um ficheiro de recurso Win32 na assembly compilada, especifique o nome do ficheiro de recurso Win32 na Win32Resource propriedade.
Note
Essa classe contém uma demanda de link e uma demanda de herança no nível de classe que se aplica a todos os membros. A SecurityException é lançado quando o chamador imediato ou a classe derivada não tem permissão de confiança plena. Para detalhes sobre exigências de segurança, consulte Exigências de Ligação e Exigências de Herança.
Construtores
| Name | Description |
|---|---|
| CompilerParameters() |
Inicializa uma nova instância da CompilerParameters classe. |
| CompilerParameters(String[], String, Boolean) |
Inicializa uma nova instância da CompilerParameters classe usando os nomes de assembly especificados, o nome de saída e um valor que indica se deve incluir informação de depuração. |
| CompilerParameters(String[], String) |
Inicializa uma nova instância da CompilerParameters classe usando os nomes de assembly especificados e o nome do ficheiro de saída. |
| CompilerParameters(String[]) |
Inicializa uma nova instância da CompilerParameters classe usando os nomes de assembly especificados. |
Propriedades
| Name | Description |
|---|---|
| CompilerOptions |
Obtém ou define argumentos opcionais na linha de comandos para usar ao invocar o compilador. |
| CoreAssemblyFileName |
Recebe ou define o nome do núcleo ou conjunto padrão que contém tipos básicos como Object, String, ou Int32. |
| EmbeddedResources |
Inclui os ficheiros de recurso .NET ao compilar a saída assembly. |
| Evidence |
Obsoleto.
Especifica um objeto de evidência que representa as permissões da política de segurança para conceder a assembly compilada. |
| GenerateExecutable |
Recebe ou define um valor que indica se deve gerar um executável. |
| GenerateInMemory |
Recebe ou define um valor que indica se deve gerar a saída na memória. |
| IncludeDebugInformation |
Recebe ou define um valor que indica se deve incluir informação de depuração no executável compilado. |
| LinkedResources |
Obtém os ficheiros de recursos .NET que estão referenciados na fonte atual. |
| MainClass |
Recebe ou define o nome da classe principal. |
| OutputAssembly |
Recebe ou define o nome do conjunto de saída. |
| ReferencedAssemblies |
Obtém as assembleias referenciadas pelo projeto atual. |
| TempFiles |
Obtém ou define a coleção que contém os ficheiros temporários. |
| TreatWarningsAsErrors |
Recebe ou define um valor que indica se deve tratar os avisos como erros. |
| UserToken |
Obtém ou define o token de utilizador para usar ao criar o processo do compilador. |
| WarningLevel |
Obtém ou define o nível de aviso a partir do qual o compilador aborta a compilação. |
| Win32Resource |
Obtém ou define o nome do ficheiro de um ficheiro de recurso Win32 para ligar à assembly compilada. |
Métodos
| Name | Description |
|---|---|
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| ToString() |
Devolve uma cadeia que representa o objeto atual. (Herdado de Object) |