Welcome

首页 / 软件开发 / .NET编程技术 / .net项目的二次开发解决方案

.net项目的二次开发解决方案2012-01-16 cnblogs Lance.Liang公司原来项目的二次开发方式主要使用SQL,基本上也能满足客户的要求,优点是使用简单,只要熟悉SQL语句就可以操作,缺点是受限制太多,需要对数据库底层相当的了解,使用时容易出错,无法直接调用业务层代码等,研究了一下.net的动态编译,感觉用它来做二次开发效果应该不错的。

首先我们先做个demo来解释一下动态编译,下面这段代码的意思就是先组织一个源码字符串,然后编译执行。

动态编译简单代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
namespace ConsoleApplication6
{
class Program
{
//C#代码提供者
private static CodeDomProvider comp = new CSharpCodeProvider();
//用于调用编译器的参数
private static CompilerParameters cp = new CompilerParameters();
private static MethodInfo mi;
static void Main(string[] args)
{
StringBuilder codeBuilder = new StringBuilder();
codeBuilder.AppendLine("using System;");
codeBuilder.AppendLine("public class MyClass");
codeBuilder.AppendLine("{");
codeBuilder.AppendLine("publicvoid hello()");
codeBuilder.AppendLine("{");
codeBuilder.AppendLine("Console.WriteLine( "hello");");
codeBuilder.AppendLine("}");
codeBuilder.AppendLine("}");
//加入需要引用的程序集
cp.ReferencedAssemblies.Add("System.dll");
CompilerResults cr = comp.CompileAssemblyFromSource(cp, codeBuilder.ToString());
//如果有编译错误
if (cr.Errors.HasErrors)
{
foreach (CompilerError item in cr.Errors)
{
Console.WriteLine(item.ToString());
}
}
else
{
Assembly a = cr.CompiledAssembly; //获取已编译的程序集
Type t = a.GetType("MyClass");//利用反射获得类型
object mode = a.CreateInstance("MyClass");
mi = t.GetMethod("hello", BindingFlags.Instance | BindingFlags.Public);
mi.Invoke(mode, new object[0]); //执行方法
}
}
}
}