c#动态构建代码树

using System;
using System.IO;
using System.Text;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Diagnostics;

partial class HelloWorldCodeDOM
{
    static void Main()
    {
        CodeNamespace prgNamespace = BuildProgram();
        var compilerOptions = new CodeGeneratorOptions()
        {
            IndentString = "  ",
            BracingStyle = "C",
            BlankLinesBetweenMembers = false
        };
        var codeText = new StringBuilder();
        using (var codeWriter = new StringWriter(codeText))
        {
            CodeDomProvider.CreateProvider("c#")
              .GenerateCodeFromNamespace(
                prgNamespace, codeWriter, compilerOptions);
        }
        var script = codeText.ToString();
        Console.WriteLine(script);
        if (Debugger.IsAttached)
            Console.ReadLine();
    }
}

partial class HelloWorldCodeDOM
{
    static CodeNamespace BuildProgram()
    {
        var ns = new CodeNamespace("MetaWorld");
        var systemImport = new CodeNamespaceImport("System");
        ns.Imports.Add(systemImport);
        var programClass = new CodeTypeDeclaration("Program");
        ns.Types.Add(programClass);
        var methodMain = new CodeMemberMethod
        {
            Attributes = MemberAttributes.Static,
            Name = "Main"
        };
        methodMain.Statements.Add(
            new CodeMethodInvokeExpression(
                new CodeSnippetExpression("Console"),
                "WriteLine",
                new CodePrimitiveExpression("Hello, world!")
            )
        );
        programClass.Members.Add(methodMain);
        return ns;
    }
}
partial class HelloWorldCodeDOM
{
    //由内而外,与置顶向下设计相反(当然,下面代码可以反过来)
    static CodeNamespace BuildProgram()
    {
        var methodMain = new CodeMemberMethod                   //定义成员方法
        {
            Attributes = MemberAttributes.Static,               //成员方法特性
            Name = "Main"                                       //方法名
        };

        methodMain.Statements.Add(                              //添加成员方法的代码表达式
            //构建代码表达式
            new CodeMethodInvokeExpression(
                new CodeSnippetExpression("Console"),
                "WriteLine",
                new CodePrimitiveExpression("Hello, world!")
            )
        );

        var programClass = new CodeTypeDeclaration("Program");  //类对象
        programClass.Members.Add(methodMain);

        var ns = new CodeNamespace("MetaWorld");                //命名空间
        ns.Imports.Add(new CodeNamespaceImport("System"));      //添加引用
        ns.Types.Add(programClass);                             //添加类
        //ns.Types.Add(new CodeTypeDeclaration("TestClass"));   //添加类

        return ns;
    }
}

你可能感兴趣的:(stringwriter,CodeDomProvider,CodeNamespace)