CompilerParameters Klas
Definitie
Belangrijk
Bepaalde informatie heeft betrekking op een voorlopige productversie die aanzienlijk kan worden gewijzigd voordat deze wordt uitgebracht. Microsoft biedt geen enkele expliciete of impliciete garanties met betrekking tot de informatie die hier wordt verstrekt.
Vertegenwoordigt de parameters die worden gebruikt om een compiler aan te roepen.
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
- Overname
-
CompilerParameters
- Afgeleid
- Kenmerken
Voorbeelden
In het volgende voorbeeld wordt een CodeDOM-brongrafiek gebouwd voor een eenvoudig Hallo wereld programma. De bron wordt vervolgens opgeslagen in een bestand, gecompileerd in een uitvoerbaar bestand en uitgevoerd. De CompileCode methode illustreert hoe u de CompilerParameters klasse gebruikt om verschillende compilerinstellingen en opties op te geven.
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
Opmerkingen
Een CompilerParameters object vertegenwoordigt de instellingen en opties voor een ICodeCompiler interface.
Als u een uitvoerbaar programma compileert, moet u de GenerateExecutable eigenschap instellen op true. Wanneer GenerateExecutable is ingesteld op false, genereert de compiler een klassenbibliotheek. Standaard wordt een nieuwe CompilerParameters geïnitialiseerd met de GenerateExecutable eigenschap ingesteld op false. Als u een uitvoerbaar bestand compileert vanuit een CodeDOM-grafiek, moet een CodeEntryPointMethod bestand worden gedefinieerd in de grafiek. Als er meerdere codeinvoerpunten zijn, kunt u aangeven welke klasse het toegangspunt definieert dat moet worden gebruikt door de naam van de klasse in te stellen op de MainClass eigenschap.
U kunt een bestandsnaam opgeven voor de uitvoerassembly in de OutputAssembly eigenschap. Anders wordt een standaardnaam voor het uitvoerbestand gebruikt. Als u foutopsporingsinformatie wilt opnemen in een gegenereerde assembly, stelt u de IncludeDebugInformation eigenschap in op true. Als uw project verwijst naar assembly's, moet u de assemblynamen opgeven als items in een StringCollection set met de ReferencedAssemblies eigenschap van het gebruikte object bij het CompilerParameters aanroepen van compilatie.
U kunt een assembly compileren die naar het geheugen wordt geschreven in plaats van schijf door de GenerateInMemory eigenschap in te stellen op true. Wanneer een assembly in het geheugen wordt gegenereerd, kan uw code een verwijzing verkrijgen naar de gegenereerde assembly op basis van de CompiledAssembly eigenschap van een CompilerResults. Als een assembly naar de schijf wordt geschreven, kunt u het pad naar de gegenereerde assembly verkrijgen op basis van de PathToAssembly eigenschap van een CompilerResults.
Als u een waarschuwingsniveau wilt opgeven waarop de compilatie moet worden gestopt, stelt u de WarningLevel eigenschap in op een geheel getal dat het waarschuwingsniveau aangeeft waarop de compilatie moet worden gestopt. U kunt de compiler ook zo configureren dat de compilatie wordt gestopt als er waarschuwingen worden aangetroffen door de TreatWarningsAsErrors eigenschap in te stellen op true.
Als u een aangepaste opdrachtregelargumentenreeks wilt opgeven die moet worden gebruikt bij het aanroepen van het compilatieproces, stelt u de tekenreeks in de CompilerOptions eigenschap in. Als een Win32-beveiligingstoken is vereist om het compilerproces aan te roepen, geeft u het token op in de UserToken eigenschap. Als u .NET Framework-resourcebestanden wilt opnemen in de gecompileerde assembly, voegt u de namen van de resourcebestanden toe aan de eigenschap EmbeddedResources. Als u wilt verwijzen naar .NET Framework-resources in een andere assembly, voegt u de namen van de resourcebestanden toe aan de eigenschap LinkedResources. Als u een Win32-resourcebestand wilt opnemen in de gecompileerde assembly, geeft u de naam op van het Win32-resourcebestand in de Win32Resource eigenschap.
Note
Deze klasse bevat een koppelingsvraag en een overnamevraag op klasseniveau die van toepassing is op alle leden. Een SecurityException wordt geworpen wanneer de directe aanroeper of de afgeleide klasse geen volledig-vertrouwensmachtiging heeft. Zie Koppelingsvereisten en overnamevereisten voor meer informatie over beveiligingsvereisten.
Constructors
| Name | Description |
|---|---|
| CompilerParameters() |
Initialiseert een nieuw exemplaar van de CompilerParameters klasse. |
| CompilerParameters(String[], String, Boolean) |
Initialiseert een nieuw exemplaar van de CompilerParameters klasse met behulp van de opgegeven assemblynamen, uitvoernaam en een waarde die aangeeft of foutopsporingsgegevens moeten worden opgenomen. |
| CompilerParameters(String[], String) |
Initialiseert een nieuw exemplaar van de CompilerParameters klasse met behulp van de opgegeven assemblynamen en de naam van het uitvoerbestand. |
| CompilerParameters(String[]) |
Initialiseert een nieuw exemplaar van de CompilerParameters klasse met behulp van de opgegeven assemblynamen. |
Eigenschappen
| Name | Description |
|---|---|
| CompilerOptions |
Haalt optionele opdrachtregelargumenten op die moeten worden gebruikt bij het aanroepen van de compiler. |
| CoreAssemblyFileName |
Hiermee haalt u de naam op van de kern of standaardassembly die basistypen Objectzoals , Stringof Int32. |
| EmbeddedResources |
Hiermee haalt u de .NET resourcebestanden op die moeten worden opgenomen bij het compileren van de assembly-uitvoer. |
| Evidence |
Verouderd.
Hiermee geeft u een bewijsobject op dat de machtigingen voor het beveiligingsbeleid vertegenwoordigt om de gecompileerde assembly te verlenen. |
| GenerateExecutable |
Hiermee wordt een waarde opgehaald of ingesteld die aangeeft of een uitvoerbaar bestand moet worden gegenereerd. |
| GenerateInMemory |
Hiermee wordt een waarde opgehaald of ingesteld die aangeeft of de uitvoer in het geheugen moet worden gegenereerd. |
| IncludeDebugInformation |
Hiermee wordt een waarde opgehaald of ingesteld die aangeeft of foutopsporingsgegevens moeten worden opgenomen in het gecompileerde uitvoerbare bestand. |
| LinkedResources |
Hiermee haalt u de .NET resourcebestanden op waarnaar wordt verwezen in de huidige bron. |
| MainClass |
Hiermee haalt u de naam van de hoofdklasse op of stelt u deze in. |
| OutputAssembly |
Hiermee haalt u de naam van de uitvoerassembly op of stelt u deze in. |
| ReferencedAssemblies |
Hiermee haalt u de assembly's op waarnaar wordt verwezen door het huidige project. |
| TempFiles |
Hiermee haalt u de verzameling op die de tijdelijke bestanden bevat of stelt u deze in. |
| TreatWarningsAsErrors |
Hiermee wordt een waarde opgehaald of ingesteld die aangeeft of waarschuwingen als fouten moeten worden behandeld. |
| UserToken |
Hiermee wordt het gebruikerstoken opgehaald of ingesteld dat moet worden gebruikt bij het maken van het compilerproces. |
| WarningLevel |
Hiermee wordt het waarschuwingsniveau ophaalt of ingesteld waarop de compiler compilatie afbreekt. |
| Win32Resource |
Hiermee haalt u de bestandsnaam van een Win32-resourcebestand op of stelt u deze in om een koppeling naar de gecompileerde assembly te maken. |
Methoden
| Name | Description |
|---|---|
| Equals(Object) |
Bepaalt of het opgegeven object gelijk is aan het huidige object. (Overgenomen van Object) |
| GetHashCode() |
Fungeert als de standaardhashfunctie. (Overgenomen van Object) |
| GetType() |
Hiermee haalt u de Type huidige instantie op. (Overgenomen van Object) |
| MemberwiseClone() |
Hiermee maakt u een ondiepe kopie van de huidige Object. (Overgenomen van Object) |
| ToString() |
Retourneert een tekenreeks die het huidige object vertegenwoordigt. (Overgenomen van Object) |