命名空间: using system.codedom; using system.codedom.compiler; using microsoft.csharp; using system.io;
??private void button1_click(object sender, system.eventargs e) ??{ ???codecompileunit compileunit = new codecompileunit(); ???codenamespace samples = new codenamespace("samples"); ???samples.imports.add( new codenamespaceimport("system") ); ???compileunit.namespaces.add( samples ); ???codetypedeclaration class1 = new codetypedeclaration("class1"); ???samples.types.add(class1);
???codeentrypointmethod start = new codeentrypointmethod(); ??? ???//输出helloword ???codemethodinvokeexpression cs1 = new codemethodinvokeexpression( new ????codetypereferenceexpression("system.console"), "writeline", new ????codeprimitiveexpression("hello world!") ); ??? ???start.statements.add(cs1); ???
???class1.members.add( start ); ???//csharpcodeprovider provider = new csharpcodeprovider(); ???//icodegenerator gen = provider.creategenerator(); ???generategraph(compileunit);
??} ??public void generategraph(codecompileunit compileunit) ??{ ???// obtains an icodegenerator from a codedomprovider class. ???csharpcodeprovider provider = new csharpcodeprovider(); ???icodegenerator gen = provider.creategenerator(); ?? ???// creates a streamwriter to an output file. ???streamwriter sw = new streamwriter("d://testgraph.cs", false);
???// generates source code using the code generator. ???gen.generatecodefromcompileunit(compileunit, sw, new??? codegeneratoroptions()); ?? ???// closes the output files. ???sw.close(); ??}
??private void button2_click(object sender, system.eventargs e) ??{ ???compilecode("d://testgraph.cs"); ??} ??//编辑生成exe ??public compilerresults compilecode(string filepath) ??{ ???// obtains an icodecompiler from a codedomprovider class. ???csharpcodeprovider provider = new csharpcodeprovider(); ???icodecompiler compiler = provider.createcompiler();
???// configures a compiler parameters object which links system.dll and ???// generates a file name based on the specified source file name. ???compilerparameters cp = new compilerparameters(new string[] {"system.dll"}, filepath.substring(0, filepath.lastindexof(".")+1)+"exe", false);
???// indicates that an executable rather than a .dll should be generated. ???cp.generateexecutable = true;