C#动态执行代码(改编)===AAA
作者:互联网
/* 初学C#,好多概念不太清晰,手头项目需要用到动态代码执行,网上搜了一堆,觉得下面这个比较合我用,就拿过来改了一下.
本来还应该加上代码正确性检测的(目前的情况是,如果动态代码有错误,实际反映出来的错误信息有可能是"未能加载程序或文件集....或它的某一个依赖项,系统找不到指定的文件", 结果造成被误导了,汗.)
先凑合着用. 到后面再修改增加其他功能.
// 参考自 http://www.cnblogs.com/kidfruit/ 地精实验室
*/
using System; using System.Collections.Generic; using System.Reflection; using System.Text; using System.CodeDom; using System.CodeDom.Compiler; namespace Dynamic { #region DynamicClass 动态运行代码类 /// <summary> /// 动态运行代码类 /// </summary> public class DynamicClass { #region Exec (code) 动态运行代码 /// <summary> /// 动态运行代码 /// </summary> /// <param name="code">动态代码(主体即可),系统会自动加上包含文件,名字空间,临时运行类名,临时运行函数名</param> /// <returns>装箱返回对象</returns> public static object Exec(string code) { string strNamespace = "DynamicClass"; string strDynamicClass = "Temp_Dynamic_Exec"; string strDynamicFuncation = "Temp_Dynamic_ExecScript"; CompilerParameters vCompilerParameters = new CompilerParameters(); vCompilerParameters.GenerateExecutable = false; vCompilerParameters.GenerateInMemory = true; vCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll"); code += "\n return \"\";\n"; string vSource = "using System;\n" + "using System.Windows.Forms; \n" + "namespace " + strNamespace + "\n{\n" + " public class " + strDynamicClass + "\n" + " {\n" + " public object " + strDynamicFuncation + "()\n" + " {\n" + "" + "" + code + "\n" + " }\n" + " }\n}\n"; CompilerResults vCompilerResults = CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromSource(vCompilerParameters, vSource); Assembly vAssembly = vCompilerResults.CompiledAssembly; object vTemp = vAssembly.CreateInstance(strNamespace + "." + strDynamicClass); MethodInfo vTest = vTemp.GetType().GetMethod(strDynamicFuncation); return vTest.Invoke(vTemp, null); } #endregion } #endregion }
标签:AAA,string,C#,代码,System,vCompilerParameters,using,动态,改编 来源: https://blog.csdn.net/u014090257/article/details/110472257