当前位置:编程文档 >> C# >> 利用CodeDOM来实现.NET Scripts
首页

利用CodeDOM来实现.NET Scripts

所属类别:C#
推荐指数:★★☆
文档人气:3
本周人气:2
发布日期:2008-8-2
近来想设计在公司的系统中加入一些动态的脚本元素,经过查资料做DEMO,总结出的在.NET平台利用CodeDOM做的动态执行代码,也是非常高效实用,真是令我惊叹之极!如果您有使用过ActiveReport的Sripts功能,即可联想起来,ActiveReport厂商也是充分利用了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;
}
}
}";
//声明C#或VB的CodeDOM
CSharpCodeProvider CP = new CSharpCodeProvider();
ICodeCompiler CCL = CP.CreateCompiler();

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

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

//执行动态代码程式集
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"});

文档说明:

     

相关文档


读取评论列表……