滑兔

博客园 首页 新随笔 联系 订阅 管理
在C#中,可以利用相应的动态编译技术来支持用户的二次开发或者支持用户的公式编辑,相应的代码如下: using System;
using System.Text;
 using System.Reflection;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
public class CSharpScript
{
 private CompilerParameters compilerParams;
 public CSharpScript()
{
compilerParams = new CompilerParameters();
SetCompilerOption();
SetReferencedAssemblies();
}
 private void SetCompilerOption()
{
compilerParams.CompilerOptions = "/target:library /optimize";
compilerParams.GenerateInMemory = true;
compilerParams.IncludeDebugInformation = false;
}
private void SetReferencedAssemblies()
{
 compilerParams.ReferencedAssemblies.Add("mscorlib.dll");
compilerParams.ReferencedAssemblies.Add("System.dll");
 compilerParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");
}
public object Evaluate(string CSharpScriptCode)
{
 Assembly GeneratedAssembly = Compile(GetCompleteCode(CSharpScriptCode));
return ExecuteMethod(GeneratedAssembly);
}
private string TempClass=@"
public class TempClass {{
 public static object CSharpScript()
 {{
 return {0};
}}
}}";
 private string GetCompleteCode(string CSharpScriptCode)
{
StringBuilder code = new StringBuilder();
code.AppendFormat(TempClass,CSharpScriptCode);
return code.ToString();
}
private Assembly Compile(string Code)
{
ICodeCompiler compiler = new CSharpCodeProvider().CreateCompiler(); //若使用VB.NET語法,則改成VBCodeProvider
 CompilerResults results = compiler.CompileAssemblyFromSource(compilerParams,Code);
return results.CompiledAssembly;
}
 private object ExecuteMethod(Assembly Asm)
{
object TempClassObject=Asm.CreateInstance("TempClass");
Type TempClassType=TempClassObject.GetType();
return TempClassType.GetMethod("CSharpScript").Invoke(TempClassObject,null);
}
}
public class MyClass { public static void Main()
 {
CSharpScript CSharpScript=new CSharpScript();
Console.WriteLine(CSharpScript.Evaluate("1+2+3"));
CSharpScript.Evaluate("System.Windows.Forms.MessageBox.Show(\"Test\")");
}
}
posted on 2004-10-18 14:03  sneak  阅读(2152)  评论(2)    收藏  举报