利用CodeDOM来实现.NET Scripts

近来想设计在公司的系统中加入一些动态的脚本元素,经过查资料做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"});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值