CompilerParameters Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Представляет параметры, используемые для вызова компилятора.
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
- Производный
- Атрибуты
Примеры
В следующем примере создается исходный граф CodeDOM для простой программы Hello World. Затем источник сохраняется в файл, компилируется в исполняемый файл и выполняется. Метод CompileCode иллюстрирует использование CompilerParameters класса для указания различных параметров и параметров компилятора.
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. Если проект ссылается на любые сборки, необходимо указать имена сборок в качестве элементов в наборе StringCollectionReferencedAssemblies свойств используемого CompilerParameters при вызове компиляции.
Чтобы скомпилировать сборку, записанную в память, а не на диск, установите для свойства GenerateInMemory значение true. При создании сборки в памяти код может получить ссылку на создаваемую сборку из свойства CompiledAssembly объекта CompilerResults. Если сборка записывается на диск, можно получить путь к созданной сборке из PathToAssembly свойства a CompilerResults.
Чтобы указать уровень предупреждения, на котором следует прекратить компиляцию, задайте свойство WarningLevel как целое число, представляющее уровень предупреждения для прекращения компиляции. Вы также можете настроить компилятор для прекращения компиляции при возникновении предупреждений, задав для свойства значение TreatWarningsAsErrors в true.
Чтобы указать пользовательскую строку аргументов командной строки, которую следует использовать при вызове процесса компиляции, задайте строку в свойстве CompilerOptions. Если для вызова процесса компилятора требуется маркер безопасности Win32, задайте этот маркер в свойстве UserToken. Чтобы включить файлы ресурсов .NET Framework в скомпилированную сборку, добавьте имена файлов ресурсов в EmbeddedResources свойство. Чтобы ссылаться на ресурсы .NET Framework в другой сборке, добавьте имена файлов ресурсов в LinkedResources свойство. Чтобы включить файл ресурсов Win32 в скомпилированную сборку, укажите имя файла ресурсов Win32 в свойстве Win32Resource .
Замечание
Этот класс содержит запрос ссылки и запрос наследования на уровне класса, которые применяются ко всем членам. SecurityException возникает, когда ни непосредственный вызывающий объект, ни производный класс не имеют разрешения на полное доверие. Дополнительные сведения о требованиях к безопасности см. в разделе "Ссылки" и "Запросы на наследование".
Конструкторы
| Имя | Описание |
|---|---|
| CompilerParameters() |
Инициализирует новый экземпляр класса CompilerParameters. |
| CompilerParameters(String[], String, Boolean) |
Инициализирует новый экземпляр CompilerParameters класса, используя указанные имена сборок, имя вывода и значение, указывающее, следует ли включать сведения об отладке. |
| CompilerParameters(String[], String) |
Инициализирует новый экземпляр CompilerParameters класса, используя указанные имена сборок и имя выходного файла. |
| CompilerParameters(String[]) |
Инициализирует новый экземпляр CompilerParameters класса с помощью указанных имен сборок. |
Свойства
| Имя | Описание |
|---|---|
| CompilerOptions |
Возвращает или задает необязательные аргументы командной строки, используемые при вызове компилятора. |
| CoreAssemblyFileName |
Возвращает или задает имя основной или стандартной сборки, содержащей базовые типы, например Object, Stringили Int32. |
| EmbeddedResources |
Возвращает файлы ресурсов .NET для включения при компиляции выходных данных сборки. |
| Evidence |
Устаревшие..
Указывает объект доказательства, представляющий разрешения политики безопасности для предоставления скомпилированной сборки. |
| GenerateExecutable |
Возвращает или задает значение, указывающее, следует ли создавать исполняемый файл. |
| GenerateInMemory |
Возвращает или задает значение, указывающее, следует ли создавать выходные данные в памяти. |
| IncludeDebugInformation |
Возвращает или задает значение, указывающее, следует ли включать сведения отладки в скомпилированный исполняемый файл. |
| LinkedResources |
Возвращает файлы ресурсов .NET, на которые ссылается текущий источник. |
| MainClass |
Возвращает или задает имя основного класса. |
| OutputAssembly |
Возвращает или задает имя выходной сборки. |
| ReferencedAssemblies |
Возвращает сборки, на которые ссылается текущий проект. |
| TempFiles |
Возвращает или задает коллекцию, содержащую временные файлы. |
| TreatWarningsAsErrors |
Возвращает или задает значение, указывающее, следует ли рассматривать предупреждения как ошибки. |
| UserToken |
Возвращает или задает маркер пользователя, используемый при создании процесса компилятора. |
| WarningLevel |
Возвращает или задает уровень предупреждения, на котором компилятор прерывает компиляцию. |
| Win32Resource |
Возвращает или задает имя файла ресурса Win32, чтобы связаться с скомпилированной сборкой. |
Методы
| Имя | Описание |
|---|---|
| Equals(Object) |
Определяет, равен ли указанный объект текущему объекту. (Унаследовано от Object) |
| GetHashCode() |
Служит хэш-функцией по умолчанию. (Унаследовано от Object) |
| GetType() |
Возвращает Type текущего экземпляра. (Унаследовано от Object) |
| MemberwiseClone() |
Создает неглубокую копию текущей Object. (Унаследовано от Object) |
| ToString() |
Возвращает строку, представляющую текущий объект. (Унаследовано от Object) |