跟小D每日学口语

CodeDom的使用

//定义需要动态执行的C#或VB代码字符串:
string code=@"using System;
using System.Windows.Forms;
namespace TestDemo
{
public class MyDemo
{
string name;
public MyDemo(string name)
{
this.name=name;
}

public string TestFun(string arg0,string arg1)
{
MessageBox.Show(arg0+arg1);
return arg0+arg1;
}
}
}";

//设置编译参数,加入所需的组件
CompilerParameters CPs = new CompilerParameters();
CPs.ReferencedAssemblies.Add("System.dll");
CPs.ReferencedAssemblies.Add("System.Windows.Forms.dll");
CPs.GenerateInMemory = true;
CPs.OutputAssembly = "MyDemo";

//***1**** 1 和 2选其一,在FrameWork3.5中用2中的代码

//声明C#或VB的CodeDOM
CSharpCodeProvider CP = new CSharpCodeProvider();
ICodeCompiler CCL = CP.CreateCompiler();  //这里在3.5中已过期了


//开始编译
CodeSnippetCompileUnit CCU = new CodeSnippetCompileUnit(code);
CompilerResults CRs = CCL.CompileAssemblyFromDom(CPs, CCU);
//*******

//***2****

//CodeDomProvider cdp = CodeDomProvider.CreateProvider("CSharp");
//CompilerResults CRs = cdp.CompileAssemblyFromSource(CPs, new string[] { code });

//********


//执行动态代码程式集
Type type = CRs.CompiledAssembly.GetType("TestDemo.MyDemo");
object obj = CRs.CompiledAssembly.CreateInstance("TestDemo.MyDemo", false, BindingFlags.Default,
null, new object[] { "MyName" }, CultureInfo.CurrentCulture, null);
type.InvokeMember("TestFun", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod,
null, obj, new object[] { "user","01"});

posted @ 2009-01-13 15:11  javak  阅读(496)  评论(0)    收藏  举报