CodeDOM
De Banane Atomic
Aller à la navigationAller à la recherche
Permet de générer du code au runtime.
// création de l'arborescence: CodeCompileUnit, Namespace, Classe, Méthode CodeCompileUnit compileUnit = new CodeCompileUnit(); CodeNamespace myNamespace = new CodeNamespace("MyNamespace"); myNamespace.Imports.Add(new CodeNamespaceImport("System")); CodeTypeDeclaration myClass = new CodeTypeDeclaration("MyClass"); CodeEntryPointMethod start = new CodeEntryPointMethod(); CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression( new CodeTypeReferenceExpression("Console"), "WriteLine", new CodePrimitiveExpression("Hello World!")); compileUnit.Namespaces.Add(myNamespace); myNamespace.Types.Add(myClass); myClass.Members.Add(start); start.Statements.Add(cs1); // génération d'un fichier contenant le code au format C# CSharpCodeProvider provider = new CSharpCodeProvider(); using (StreamWriter sw = new StreamWriter("HelloWorld.cs", false)) { IndentedTextWriter tw = new IndentedTextWriter(sw, " "); provider.GenerateCodeFromCompileUnit(compileUnit, tw, new CodeGeneratorOptions()); tw.Close(); } |
HelloWorld.cs |
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace MyNamespace { using System; public class MyClass { public static void Main() { Console.WriteLine("Hello World!"); } } } |