首页 > 开发 > 综合 > 正文

使用CodeDom来生成.cs文件

2024-07-21 02:17:15
字体:
来源:转载
供稿:网友
在学使用codedom来动态生成.cs文件,使用帮助里的例子,代码居然编译不通过
自己修改,调试通过,整理后主要代码如下:

命名空间:
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;

???// invokes compilation.
???compilerresults cr = compiler.compileassemblyfromfile(cp, filepath);??

???// returns the results of compilation.
???return cr;???????
??}

帮助里的例子在:
.net framework->使用 .net framework 编程->动态生成和编译以多种语言表示的源代码

商业源码热门下载www.html.org.cn

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表