次の方法で共有


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
派生
属性

次の例では、単純な Hello World プログラム用の CodeDOM ソース グラフを作成します。 その後、ソースがファイルに保存され、実行可能ファイルにコンパイルされて実行されます。 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 に設定する必要があります。 GenerateExecutablefalse に設定すると、コンパイラによってクラス ライブラリが生成されます。 既定では、新規の CompilerParameters は、GenerateExecutable プロパティを false に設定して初期化されます。 CodeDOM グラフから実行可能ファイルをコンパイルする場合、グラフに CodeEntryPointMethod を定義する必要があります。 複数のコード エントリ ポイントがある場合は、クラスの名前を MainClass プロパティに設定することで、使用するエントリ ポイントを定義するクラスを指定できます。

出力アセンブリのファイル名は、 OutputAssembly プロパティで指定できます。 指定しない場合、既定の出力ファイル名が使用されます。 生成されたアセンブリにデバッグ情報を含めるには、 IncludeDebugInformation プロパティを true に設定します。 プロジェクトでアセンブリを参照する場合は、コンパイルの呼び出し時に使用されるCompilerParametersReferencedAssemblies プロパティに設定されたStringCollection内の項目としてアセンブリ名を指定する必要があります。

GenerateInMemory プロパティを true に設定することで、ディスクではなくメモリに書き込まれるアセンブリをコンパイルできます。 アセンブリをメモリに生成すると、CompiledAssemblyCompilerResults プロパティから生成されたアセンブリの参照がコードに与えられることがあります。 アセンブリをディスクに書き込む場合、PathToAssemblyCompilerResults プロパティから生成されたアセンブリのパスを取得できます。

コンパイルを中止する警告レベルを指定するには、コンパイルを中止する警告レベルを表す整数に WarningLevel プロパティを設定します。 TreatWarningsAsErrors プロパティを true に設定すると、警告が出た場合にコンパイルを中止するようにコンパイラを設定することもできます。

コンパイル プロセスを呼び出すときに使用するカスタムのコマンドライン引数を指定するには、CompilerOptions プロパティに文字列を設定します。 コンパイラ プロセスの呼び出しに Win32 セキュリティ トークンが必要な場合、UserToken プロパティにトークンを指定します。 コンパイル済みアセンブリに .NET Framework リソース ファイルを含めるには、リソース ファイルの名前を EmbeddedResources プロパティに追加します。 別のアセンブリ内の .NET Framework リソースを参照するには、リソース ファイルの名前を LinkedResources プロパティに追加します。 コンパイル済みアセンブリに Win32 リソース ファイルを含めるには、 Win32Resource プロパティで Win32 リソース ファイルの名前を指定します。

このクラスには、すべてのメンバーに適用されるクラス レベルでのリンク要求と継承要求が含まれます。 直接の呼び出し元か派生クラスのいずれかに完全信頼アクセス許可がない場合、SecurityException がスローされます。 セキュリティ要求の詳細については、「 リンクの要求 と継承の 要求」を参照してください。

コンストラクター

名前 説明
CompilerParameters()

CompilerParameters クラスの新しいインスタンスを初期化します。

CompilerParameters(String[], String, Boolean)

指定したアセンブリ名、出力名、およびデバッグ情報を含めるかどうかを示す値を使用して、 CompilerParameters クラスの新しいインスタンスを初期化します。

CompilerParameters(String[], String)

指定したアセンブリ名と出力ファイル名を使用して、 CompilerParameters クラスの新しいインスタンスを初期化します。

CompilerParameters(String[])

指定したアセンブリ名を使用して、 CompilerParameters クラスの新しいインスタンスを初期化します。

プロパティ

名前 説明
CompilerOptions

コンパイラを呼び出すときに使用するオプションのコマンド ライン引数を取得または設定します。

CoreAssemblyFileName

ObjectStringInt32などの基本型を含むコアアセンブリまたは標準アセンブリの名前を取得または設定します。

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)

適用対象