原文:http://www.cnblogs.com/minbear/archive/2004/05/12/9058.aspx
将資料庫中的.net原碼進行動态編譯及調用~
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);