CompilerParameters 類別
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
表示用來叫用編譯器的參數。
public ref class CompilerParameters
public class CompilerParameters
[System.Runtime.InteropServices.ComVisible(false)]
public class CompilerParameters
[System.Serializable]
public class CompilerParameters
type CompilerParameters = class
[<System.Runtime.InteropServices.ComVisible(false)>]
type CompilerParameters = class
[<System.Serializable>]
type CompilerParameters = class
Public Class CompilerParameters
- 繼承
-
CompilerParameters
- 衍生
- 屬性
範例
下列範例會建置簡單 Hello World 程式的 CodeDOM 原始程式圖形。 然後,來源會儲存至檔案、編譯成可執行檔,然後執行。 方法 CompileCode
說明如何使用 CompilerParameters 類別來指定各種編譯程式設定和選項。
using namespace System;
using namespace System::CodeDom;
using namespace System::CodeDom::Compiler;
using namespace System::Collections;
using namespace System::ComponentModel;
using namespace System::IO;
using namespace System::Diagnostics;
// Build a Hello World program graph using System.CodeDom types.
static CodeCompileUnit^ BuildHelloWorldGraph()
{
// Create a new CodeCompileUnit to contain the program graph.
CodeCompileUnit^ compileUnit = gcnew CodeCompileUnit;
// Declare a new namespace called Samples.
CodeNamespace^ samples = gcnew 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( gcnew CodeNamespaceImport( "System" ) );
// Declare a new type called Class1.
CodeTypeDeclaration^ class1 = gcnew 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 = gcnew CodeEntryPointMethod;
// Create a type reference for the System::Console class.
CodeTypeReferenceExpression^ csSystemConsoleType =
gcnew CodeTypeReferenceExpression( "System.Console" );
// Build a Console::WriteLine statement.
CodeMethodInvokeExpression^ cs1 = gcnew CodeMethodInvokeExpression(
csSystemConsoleType, "WriteLine",
gcnew CodePrimitiveExpression( "Hello World!" ) );
// Add the WriteLine call to the statement collection.
start->Statements->Add( cs1 );
// Build another Console::WriteLine statement.
CodeMethodInvokeExpression^ cs2 = gcnew CodeMethodInvokeExpression(
csSystemConsoleType, "WriteLine",
gcnew 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.
CodeMethodReferenceExpression^ csReadLine = gcnew CodeMethodReferenceExpression(
csSystemConsoleType, "ReadLine" );
CodeMethodInvokeExpression^ cs3 = gcnew CodeMethodInvokeExpression(
csReadLine,gcnew array<CodeExpression^>(0) );
// Add the ReadLine statement.
start->Statements->Add( cs3 );
// Add the code entry point method to the Members collection
// of the type.
class1->Members->Add( start );
return compileUnit;
}
static String^ GenerateCode( CodeDomProvider^ provider, CodeCompileUnit^ compileunit )
{
// Build the source file name with the language extension (vb, cs, js).
String^ sourceFile = String::Empty;
if ( provider->FileExtension->StartsWith( "." ) )
{
sourceFile = String::Concat( "HelloWorld", provider->FileExtension );
}
else
{
sourceFile = String::Concat( "HelloWorld.", provider->FileExtension );
}
// Create a TextWriter to a StreamWriter to an output file.
IndentedTextWriter^ tw = gcnew IndentedTextWriter(
gcnew StreamWriter( sourceFile,false )," " );
// Generate source code using the code generator.
provider->GenerateCodeFromCompileUnit( compileunit, tw, gcnew CodeGeneratorOptions );
// Close the output file.
tw->Close();
return sourceFile;
}
static bool CompileCode( CodeDomProvider^ provider,
String^ sourceFile,
String^ exeFile )
{
CompilerParameters^ cp = gcnew CompilerParameters;
if ( !cp)
{
return false;
}
// 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 = gcnew 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 );
for each ( CompilerError^ ce in cr->Errors )
{
Console::WriteLine( " {0}", ce->ToString() );
Console::WriteLine();
}
}
else
{
Console::WriteLine( "Source {0} built into {1} successfully.",
sourceFile, cr->PathToAssembly );
}
// Return the results of compilation.
if ( cr->Errors->Count > 0 )
{
return false;
}
else
{
return true;
}
}
[STAThread]
void main()
{
String^ exeName = "HelloWorld.exe";
CodeDomProvider^ provider = nullptr;
Console::WriteLine( "Enter the source language for Hello World (cs, vb, etc):" );
String^ inputLang = Console::ReadLine();
Console::WriteLine();
if ( CodeDomProvider::IsDefinedLanguage( inputLang ) )
{
CodeCompileUnit^ helloWorld = BuildHelloWorldGraph();
provider = CodeDomProvider::CreateProvider( inputLang );
if ( helloWorld && provider )
{
String^ sourceFile = GenerateCode( provider, helloWorld );
Console::WriteLine( "HelloWorld source code generated." );
if ( CompileCode( provider, sourceFile, exeName ) )
{
Console::WriteLine( "Starting HelloWorld executable." );
Process::Start( exeName );
}
}
}
if ( provider == nullptr )
{
Console::WriteLine( "There is no CodeDomProvider for the input language." );
}
}
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
備註
CompilerParameters物件代表介面的ICodeCompiler設定和選項。
如果您要編譯可執行的程式,則必須將 GenerateExecutable 屬性設定為 true
。
GenerateExecutable當 設定為 false
時,編譯程式將會產生類別庫。 根據預設,新的 CompilerParameters 會初始化,並將其 GenerateExecutable 屬性設定為 false
。 如要從 CodeDOM 圖表編譯可執行檔,即必須在圖表中定義 CodeEntryPointMethod。 如果有多個程式代碼進入點,您可以藉由將類別的名稱設定為 屬性,來指出定義要使用的進入點的 MainClass 類別。
您可以在 屬性中 OutputAssembly 指定輸出元件的檔案名。 否則,會使用預設的輸出檔名稱。 若要在產生的元件中包含偵錯資訊,請將 IncludeDebugInformation 屬性設定為 true
。 如果您的項目參考任何元件,您必須在叫用編譯時,將元件名稱指定為集合ReferencedAssemblies中所使用的 屬性CompilerParameters中的StringCollection專案。
您可以將 屬性true
設定為 ,以編譯寫入記憶體而非磁碟的GenerateInMemory元件。 當組件在記憶體中產生時,您的程式碼可從 CompilerResults 的 CompiledAssembly 屬性取得所產生組件的參考。 如果元件寫入磁碟,您可以從 的CompilerResults屬性取得所產生元件PathToAssembly的路徑。
若要指定中斷編譯的警告層級,請將 WarningLevel 屬性設為整數,表示要中斷編譯的警告層級。 如果遇到警告,您也可以將 屬性設定 TreatWarningsAsErrors 為 true
,讓編譯程式停止編譯。
若要在叫用編譯處理序時指定使用的自訂命令列引數字串,請在 CompilerOptions 屬性中設定字串。 如果需要 Win32 安全性權杖才能叫用編譯器處理序,請在 UserToken 屬性中指定權杖。 若要在編譯的元件中包含 .NET Framework 資源檔,請將資源文件的名稱新增至 EmbeddedResources 屬性。 若要參考另一個元件中的 .NET Framework 資源,請將資源文件的名稱新增至 LinkedResources 屬性。 若要在編譯的元件中包含 Win32 資源檔,請在 屬性中 Win32Resource 指定 Win32 資源文件的名稱。
注意
這個類別包含套用至所有成員之類別層級的連結需求和繼承需求。 SecurityException當立即呼叫端或衍生類別沒有完全信任權限時,就會擲回 。 如需安全性需求的詳細資訊,請參閱 連結需求 和 繼承需求。
建構函式
CompilerParameters() |
初始化 CompilerParameters 類別的新執行個體。 |
CompilerParameters(String[]) |
使用指定的組件名稱來初始化 CompilerParameters 類別的新執行個體。 |
CompilerParameters(String[], String) |
使用指定的組件名稱和輸出檔名稱來初始化 CompilerParameters 類別的新執行個體。 |
CompilerParameters(String[], String, Boolean) |
使用指定的組件名稱、輸出名稱和指示是否要包含偵錯資訊的數值,來初始化 CompilerParameters 類別的新執行個體。 |
屬性
CompilerOptions |
取得或設定在叫用編譯器時,要使用的選擇性命令列引數。 |
CoreAssemblyFileName | |
EmbeddedResources |
取得編譯組件輸出時要包含的 .NET 資源檔。 |
Evidence |
已淘汰.
指定舉證物件,這個物件表示授與編譯過的組件的安全性原則權限。 |
GenerateExecutable |
取得或設定值,指出是否產生可執行檔。 |
GenerateInMemory |
取得或設定值,指出是否在記憶體中產生輸出。 |
IncludeDebugInformation |
取得或設定值,指出是否要在已編譯的可執行檔中包含偵錯資訊。 |
LinkedResources |
取得在目前來源中參考的 .NET 資源檔。 |
MainClass |
取得或設定主要類別的名稱。 |
OutputAssembly |
取得或設定輸出組件的名稱。 |
ReferencedAssemblies |
取得目前專案所參考的組件。 |
TempFiles |
取得或設定包含暫存檔案的集合。 |
TreatWarningsAsErrors |
取得或設定值,指出是否將警告當做錯誤。 |
UserToken |
取得或設定在建立編譯器處理序 (Process) 時要使用的使用者語彙基元 (Token)。 |
WarningLevel |
取得或設定編譯器中止編譯所在的警告層級。 |
Win32Resource |
取得或設定要連結至已編譯組件內之 Win32 資源檔的檔名。 |
方法
Equals(Object) |
判斷指定的物件是否等於目前的物件。 (繼承來源 Object) |
GetHashCode() |
做為預設雜湊函式。 (繼承來源 Object) |
GetType() |
取得目前執行個體的 Type。 (繼承來源 Object) |
MemberwiseClone() |
建立目前 Object 的淺層複製。 (繼承來源 Object) |
ToString() |
傳回代表目前物件的字串。 (繼承來源 Object) |