下面的代码用于在本程序中,根据输入的代码生成另一个程序:HelloWorld.exe
创建一个Windows Form程序WindowsFormsApplication1,添加下面的引用:
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
全部代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// 创建编译器对象
CSharpCodeProvider p = new CSharpCodeProvider();
ICodeCompiler cc = p.CreateCompiler();
// 设置编译参数
CompilerParameters options = new CompilerParameters();
options.ReferencedAssemblies.Add("System.dll");
//CurrentNameSpace.Imports.Add (new CodeNamespaceImport("System"));引入命名空间
// CurrentNameSpace.Imports.Add (new CodeNamespaceImport("System.Text"));
options.GenerateExecutable = true;
options.OutputAssembly = "HelloWorld.exe";
string code = @"using System;
using System.Collections.Generic;
using System.Text;
namespace Hello
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("+"/""+"AA"+"/""+"); Console.Read(); } }}";
CodeSnippetCompileUnit cu = new CodeSnippetCompileUnit(code);
// 开始编译
CompilerResults cr = cc.CompileAssemblyFromDom(options, cu);
// 显示编译信息
if (cr.Errors.Count == 0)
{
Console.WriteLine("/"{0}/" 编译成功!", cr.CompiledAssembly.Location);
Console.ReadLine();
}
else
{
Console.WriteLine("编译错误:");
foreach (CompilerError error in cr.Errors)
Console.WriteLine(" {0}", error);
}
Console.WriteLine("按任意键退出...");
Console.ReadLine();
}
}
}
编译后运行,可以看到在debug目录下,生成下面的程序:
WindowsFormsApplication1.exe
运行该程序,点击button1,生成下面的程序:
HelloWorld.exe
运行HelloWorld.exe后,可以看到我们要求的结果:在DOS窗口上输出“AA”的字符。
网上的另一篇文章:CodeDom:语言的界限在这里消失 http://www.chinaitpower.com/2006Aug/2006-09-30/216245.html
可提供参考