Forráskód létrehozása és fordítása CodeDOM-gráfból
A System.CodeDom.Compiler névtér interfészeket biztosít a CodeDOM objektumgráfokból származó forráskód létrehozásához és a fordítás támogatott fordítókkal történő kezeléséhez. A kódszolgáltató egy CodeDOM-gráf alapján képes forráskódot létrehozni egy adott programozási nyelven. A származtatott CodeDomProvider osztályok általában metódusokat biztosítanak a szolgáltató által támogatott nyelv kódjának létrehozásához és összeállításához.
Forráskód létrehozása CodeDOM-kódszolgáltató használatával
Ha egy adott nyelven szeretne forráskódot létrehozni, szüksége van egy CodeDOM-gráfra, amely a létrehozandó forráskód szerkezetét jelöli.
Az alábbi példa bemutatja, hogyan hozhat létre egy példányt CSharpCodeProvider:
CSharpCodeProvider^ provider = gcnew CSharpCodeProvider();
CSharpCodeProvider provider = new CSharpCodeProvider();
Dim provider As New CSharpCodeProvider()
A kódgenerálás gráfja általában egy CodeCompileUnit. CodeDOM-gráfot tartalmazó kód CodeCompileUnit
létrehozásához hívja meg a GenerateCodeFromCompileUnit kódszolgáltató metódusát. Ez a metódus rendelkezik egy paraméterrel TextWriter , amelyet a forráskód létrehozásához használ, ezért néha létre kell hoznia egy olyan paramétert TextWriter
, amelybe írható. Az alábbi példa azt mutatja be, hogy kódot hoz létre egy CodeCompileUnit
HelloWorld.cs nevű fájlból, és írja be a létrehozott forráskódot.
public:
static String^ GenerateCSharpCode(CodeCompileUnit^ compileunit)
{
// Generate the code with the C# code provider.
CSharpCodeProvider^ provider = gcnew CSharpCodeProvider();
// Build the output file name.
String^ sourceFile;
if (provider->FileExtension[0] == '.')
{
sourceFile = "HelloWorld" + provider->FileExtension;
}
else
{
sourceFile = "HelloWorld." + provider->FileExtension;
}
// Create a TextWriter to a StreamWriter to the output file.
StreamWriter^ sw = gcnew StreamWriter(sourceFile, false);
IndentedTextWriter^ tw = gcnew IndentedTextWriter(sw, " ");
// Generate source code using namespace the code provider.
provider->GenerateCodeFromCompileUnit(compileunit, tw,
gcnew CodeGeneratorOptions());
// Close the output file.
tw->Close();
sw->Close();
return sourceFile;
}
public static string GenerateCSharpCode(CodeCompileUnit compileunit)
{
// Generate the code with the C# code provider.
CSharpCodeProvider provider = new CSharpCodeProvider();
// Build the output file name.
string sourceFile;
if (provider.FileExtension[0] == '.')
{
sourceFile = "HelloWorld" + provider.FileExtension;
}
else
{
sourceFile = "HelloWorld." + provider.FileExtension;
}
// Create a TextWriter to a StreamWriter to the output file.
using (StreamWriter sw = new StreamWriter(sourceFile, false))
{
IndentedTextWriter tw = new IndentedTextWriter(sw, " ");
// Generate source code using the code provider.
provider.GenerateCodeFromCompileUnit(compileunit, tw,
new CodeGeneratorOptions());
// Close the output file.
tw.Close();
}
return sourceFile;
}
Public Shared Function GenerateCSharpCode(compileunit As CodeCompileUnit) As String
' Generate the code with the C# code provider.
Dim provider As New CSharpCodeProvider()
' Build the output file name.
Dim sourceFile As String
If provider.FileExtension(0) = "." Then
sourceFile = "HelloWorld" + provider.FileExtension
Else
sourceFile = "HelloWorld." + provider.FileExtension
End If
' Create a TextWriter to a StreamWriter to the output file.
Using sw As New StreamWriter(sourceFile, false)
Dim tw As New IndentedTextWriter(sw, " ")
' Generate source code Imports the code provider.
provider.GenerateCodeFromCompileUnit(compileunit, tw, _
New CodeGeneratorOptions())
' Close the output file.
tw.Close()
End Using
Return sourceFile
End Function
Szerelvények fordítása CodeDOM-kódszolgáltató használatával
Fordítás meghívása
Egy szerelvény CodeDom-szolgáltatóval történő fordításához vagy forráskóddal kell rendelkeznie ahhoz, hogy olyan nyelven fordítson, amelyhez fordítója van, vagy olyan CodeDOM-gráfot kell használnia, amelyből a forráskód lefordítható.
Ha CodeDOM-gráfból állít össze, adja át a CodeCompileUnit gráfot a CompileAssemblyFromDom kódszolgáltató metódusának. Ha a forráskódfájl olyan nyelven található, amelyet a fordító megért, adja át a forráskódot tartalmazó fájl nevét a CompileAssemblyFromFile CodeDom-szolgáltató metódusának. A forráskódot tartalmazó sztringeket olyan nyelven is átadhatja, amelyet a fordító megért a CompileAssemblyFromSource CodeDom-szolgáltató metódusának.
Fordítási paraméterek konfigurálása
A CodeDom-szolgáltató összes szabványos fordítási metódusa rendelkezik olyan típusú CompilerParameters paraméterrel, amely a fordítási lehetőségeket jelzi.
A kimeneti szerelvény fájlnevét a CompilerParameters
/> tulajdonságában adhatja meg. Ellenkező esetben a rendszer egy alapértelmezett kimeneti fájlnevet használ.
Alapértelmezés szerint a rendszer inicializál egy újat CompilerParameters
, amelynek tulajdonsága GenerateExecutable a következőre false
van állítva. Ha végrehajtható programot állít össze, a tulajdonságot a GenerateExecutable
következőre kell állítania true
: . Ha az GenerateExecutable
érték be van állítva false
, a fordító létrehoz egy osztálytárat.
Ha egy CodeDOM-gráfból állít össze végrehajtható gráfot, a gráfban meg kell határoznia azt CodeEntryPointMethod . Ha több kódbeviteli pont is van, előfordulhat, hogy a MainClassCompilerParameters
tulajdonságot a használni kívánt belépési pontot meghatározó osztály nevére kell beállítani.
Ha hibakeresési adatokat szeretne belefoglalni egy létrehozott végrehajtható fájlba, állítsa a tulajdonságot a IncludeDebugInformation következőre true
: .
Ha a projekt bármilyen összeállításra hivatkozik, a szerelvényneveket elemekként StringCollection kell megadnia a ReferencedAssemblies fordítás meghívásakor CompilerParameters
használt tulajdonságként.
A tulajdonság beállításával GenerateInMemory a memóriába írt szerelvényt nem lemezre, hanem memóriába true
fordíthatja. Amikor a rendszer létrehoz egy szerelvényt a memóriában, a kód a létrehozott szerelvényre mutató hivatkozást szerezhet be egy CompiledAssemblyCompilerResults. Ha a rendszer lemezre ír egy szerelvényt, a létrehozott szerelvény elérési útját egy PathToAssemblyCompilerResults
.
Ha egyéni parancssori argumentumsztringet szeretne megadni a fordítási folyamat meghívásához, állítsa be a karakterláncot a CompilerOptions tulajdonságban.
Ha a fordítófolyamat meghívásához Win32 biztonsági jogkivonatra van szükség, adja meg a jogkivonatot a UserToken tulajdonságban.
Ha egy Win32-erőforrásfájlt a lefordított szerelvénybe szeretne kapcsolni, adja meg a Win32-erőforrásfájl nevét a Win32Resource tulajdonságban.
Ha meg szeretne adni egy figyelmeztetési szintet, amelynél le szeretné állítani a fordítást, állítsa a WarningLevel tulajdonságot egy egész számra, amely azt a figyelmeztetési szintet jelöli, amelyen a fordítást le kell állítani. A fordítót úgy is konfigurálhatja, hogy állítsa le a fordítást, ha figyelmeztetések lépnek fel a TreatWarningsAsErrors tulajdonság true
beállításával.
Az alábbi példakód egy forrásfájl összeállítását mutatja be az osztályból CodeDomProvider származtatott CodeDom-szolgáltató használatával.
public:
static bool CompileCSharpCode(String^ sourceFile, String^ exeFile)
{
CSharpCodeProvider^ provider = gcnew CSharpCodeProvider();
// Build the parameters for source compilation.
CompilerParameters^ cp = gcnew CompilerParameters();
// Add an assembly reference.
cp->ReferencedAssemblies->Add( "System.dll" );
// Generate an executable instead of
// a class library.
cp->GenerateExecutable = true;
// Set the assembly file name to generate.
cp->OutputAssembly = exeFile;
// Save the assembly as a physical file.
cp->GenerateInMemory = false;
// 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;
}
}
public static bool CompileCSharpCode(string sourceFile, string exeFile)
{
CSharpCodeProvider provider = new CSharpCodeProvider();
// Build the parameters for source compilation.
CompilerParameters cp = new CompilerParameters();
// Add an assembly reference.
cp.ReferencedAssemblies.Add( "System.dll" );
// Generate an executable instead of
// a class library.
cp.GenerateExecutable = true;
// Set the assembly file name to generate.
cp.OutputAssembly = exeFile;
// Save the assembly as a physical file.
cp.GenerateInMemory = false;
// 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);
}
// Return the results of compilation.
if (cr.Errors.Count > 0)
{
return false;
}
else
{
return true;
}
}
Public Shared Function CompileCSharpCode(sourceFile As String, _
exeFile As String) As Boolean
Dim provider As New CSharpCodeProvider()
' Build the parameters for source compilation.
Dim cp As New CompilerParameters()
' Add an assembly reference.
cp.ReferencedAssemblies.Add("System.dll")
' Generate an executable instead of
' a class library.
cp.GenerateExecutable = true
' Set the assembly file name to generate.
cp.OutputAssembly = exeFile
' Save the assembly as a physical file.
cp.GenerateInMemory = false
' 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)
For Each ce As CompilerError In cr.Errors
Console.WriteLine(" {0}", ce.ToString())
Console.WriteLine()
Next ce
Else
Console.WriteLine("Source {0} built into {1} successfully.", _
sourceFile, cr.PathToAssembly)
End If
' Return the results of compilation.
If cr.Errors.Count > 0 Then
Return False
Else
Return True
End If
End Function
Kezdeti támogatással rendelkező nyelvek
A .NET kódfordítókat és kódgenerátorokat biztosít a következő nyelvekhez: C#, Visual Basic, C++ és JScript. A CodeDOM támogatása más nyelvekre is kiterjeszthető nyelvspecifikus kódgenerátorok és kódfordítók implementálásával.
Lásd még
Visszajelzés
https://aka.ms/ContentUserFeedback.
Hamarosan elérhető: 2024-ben fokozatosan kivezetjük a GitHub-problémákat a tartalom visszajelzési mechanizmusaként, és lecseréljük egy új visszajelzési rendszerre. További információ:Visszajelzés küldése és megtekintése a következőhöz: