日期:2014-05-19  浏览次数:21055 次

如何动态生成代码
如何动态生成代码

------解决方案--------------------
是动态编译生成可执行文件还是动态写出源代码?
------解决方案--------------------
能否再明确一些?
------解决方案--------------------
参见MSDN发出动态程序集相关章节
------解决方案--------------------
摘录:《程序员秘书》--源代码--进程--动态生成源代码并编译
6、在Form1.cs的视图设计器中,选中button1,在属性框中选中事件,双击Click,在Form1.cs的代码设计器中,添加修改如下代码
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog FolderBrowserDialog1 = new FolderBrowserDialog();
if (FolderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
FilePath = FolderBrowserDialog1.SelectedPath;

CodeCompileUnit compileUnit = new CodeCompileUnit();//可以编译的源代码为模型的 CodeDOM 对象图
CodeNamespace samples = new CodeNamespace( "Samples ");//定义命名空间
samples.Imports.Add(new CodeNamespaceImport( "System "));//导入命名空间
samples.Imports.Add(new CodeNamespaceImport( "System.Threading "));
compileUnit.Namespaces.Add(samples); //将代码元素链接到对象图中
CodeTypeDeclaration class1 = new CodeTypeDeclaration( "Class1 ");//定义类型
samples.Types.Add(class1); //将名为 class1 的类添加到名为 samples 的 CodeNamespace

CodeEntryPointMethod start = new CodeEntryPointMethod();//定义可执行程序的代码入口点
CodeMethodInvokeExpression cs1 = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression( "System.Console "), "WriteLine ", new CodePrimitiveExpression( "Hello World! "));//显示信息
CodeMethodInvokeExpression cs2 = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression( "Thread "), "Sleep ", new CodePrimitiveExpression(5000));//暂停5秒
start.Statements.Add(cs1);
start.Statements.Add(cs2);
class1.Members.Add(start);//Start 的入口点方法添加到 class1 的 Members 集合

string CSfilename = GenerateCSharpCode(compileUnit);//使用 CodeDOM 代码生成器生成源代码
CompileCSharpCode(CSfilename, FilePath + "\\HelloWorld.exe ");//使用 CodeDOM 代码提供程序编译程序集
}
}

立即成为编程经验丰富的程序员不是梦,详见:http://www.psec.net.cn
------解决方案--------------------
使用CodeDom

/// <summary>
/// 创建相应脚本语言的编译器
/// </summary>
private void createCompiler(string strLanguage, bool debugMode, string strAssemblyFileName)
{
this.theParameters = new CompilerParameters();
this.theParameters.OutputAssembly = System.IO.Path.Combine(System.IO.Path.GetTempPath(), strAssemblyFileName + ".dll ");
this.theParameters.GenerateExecutable = false;
this.theParameters.GenerateInMemory = true;
if(debugMode)
{
this.theParameters.IncludeDebugInformation = true;
this.theParameters.CompilerOptions += "/define:TRACE=1 /define:DEBUG=1 ";
}
else
{
this.theParameters.IncludeDebugInformation = false;
this.theParameters.CompilerOptions += "/define:TRACE=1 ";
}

AddReference( "System.dll ");
AddReference( "System.Data.dll ");
AddReference( "System.Xml.dll ");

strLanguage = strLanguage.ToLower();

if( "visualbasic " == strLanguage || "vb " == strLanguage)
{
theProvider = new Microsoft.VisualBasic.VBCodeProvider();
if(debugMode)
theParameters.CompilerOptions += "/debug:full /optimize- /optionexplicit+ /optionstrict+ /optioncompare:text /imports:Microsoft.VisualBasic,System,System.Collections,System.Diagnostics "