1、为了反射,定义一个接口
public interface IRunExpression { Hashtable MainRun(bool IsDebug);int Precision {set;get;}}2、生成数据库内容的dll,在这里将内容先写死,可以直接从数据库读取StringBuilder _SB = new StringBuilder();//加载引用 _SB.Append("using System; \r\n"); _SB.Append("using System.Collections ; \r\n"); _SB.Append("using System.Threading; \r\n"); _SB.Append("using System.IO; \r\n"); _SB.Append("using System.Text; \r\n"); _SB.Append("using System.Data; \r\n");//namespace开始 _SB.Append("namespace CodeCompile \r\n"); _SB.Append("{ \r\n"); _SB.Append("public class RunExpression : IRunExpression \r\n"); _SB.Append("{ \r\n"); _SB.Append("public RunExpression() \r\n"); _SB.Append("{ \r\n"); _SB.Append("} \r\n"); //简单的属性 _SB.Append("private int _Precision; \r\n"); _SB.Append("public int Precision \r\n"); _SB.Append("{ \r\n"); _SB.Append("set{_Precision=value;} \r\n"); _SB.Append("get{return _Precision;} \r\n"); _SB.Append("} \r\n");//简单方法实现 _SB.Append("public Hashtable MainRun(bool IsDebug){return new Hashtable();} \r\n"); _SB.Append(" } \r\n"); _SB.Append("} \r\n");string CodeContent = _SB.ToString(); //需要编译的内容//下面的内容需要using Microsoft.CSharp;CSharpCodeProvider _SCP = new CSharpCodeProvider(); CompilerParameters _CP = new CompilerParameters();_CP.GenerateExecutable = false;
_CP.MainClass = "CodeCompile.RunExpression";//获取生成路径:)
Assembly a1 = Assembly.GetExecutingAssembly(); string e1 = a1.CodeBase ; int m = e1.IndexOf(@"///") + 3; int n = e1.Length; e1 = e1.Substring(m,n - m); string[] all = e1.Split(new char[]{'/'}); string prefix = ""; for(int i=0;i<all.Length-1;i++) { prefix += all[i] + "/"; }_CP.OutputAssembly = prefix + "RunExpressionTest.DLL";
_CP.IncludeDebugInformation = true;
_CP.ReferencedAssemblies.Add( "System.dll" );
_CP.ReferencedAssemblies.Add( "System.Data.dll" ); _CP.ReferencedAssemblies.Add( "System.Web.dll" ); _CP.ReferencedAssemblies.Add( "System.XML.dll" ); _CP.GenerateInMemory = false;_CP.WarningLevel = 3;
_CP.TreatWarningsAsErrors = false;
_CP.CompilerOptions = "/optimize"; _CP.TempFiles = new TempFileCollection( prefix + @"\temp", true); //把编译的过程文件放到temp目录。CompilerResults _CR = _SCP.CreateCompiler().CompileAssemblyFromSource(_CP,CodeContent);
System.Collections.Specialized.StringCollection _SC = _CR.Output;
CompilerErrorCollection _EC = _CR.Errors;
3、OK,内容编译完成,下面是对它的调用string AssemblyName = "RunExpressionTest.DLL";ObjectHandle M = Activator.CreateInstance(AssemblyName,"CodeCompile.RunExpression");IRunExpression _IRE = (IRunExpression)M.Unwrap();_IRE.Precision = 2;Hashtable _HTreturn = _IRE.MainRun(true);