逍遥游

一直在想,怎样路好走一点,一直想,一直在崎岖中徘徊。
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C#中如何动态运行代码

Posted on 2007-06-08 09:13  逍遥游  阅读(813)  评论(0编辑  收藏  举报

private void Compiler(string code)
        {
            CompilerParameters vCompilerParameters = new CompilerParameters();
            vCompilerParameters.GenerateExecutable = false;
            vCompilerParameters.GenerateInMemory = true;
            vCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
            string vSource =
                "using System.Windows.Forms;\n" +
                "public class Temp\n" +
                "{\n" +
                "    public void Test()\n" +
                "    {\n" +
                "         " + code + "\n" +
                "    }\n" +
                "}\n";
            CompilerResults vCompilerResults =
                CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromSource(vCompilerParameters, vSource);

            Assembly vAssembly = vCompilerResults.CompiledAssembly;
            object vTemp = vAssembly.CreateInstance("Temp");
            MethodInfo vTest = vTemp.GetType().GetMethod("Test");
            vTest.Invoke(vTemp, null);
        }

 

string code = "int sum = 0;\nfor(int i = 0; i < 100; i++)\n{\nsum += i;\n}\nMessageBox.Show(sum.ToString());";
            Compiler(code);