码迷,mamicode.com
首页 > Windows程序 > 详细

.Net 动态编译(c# 脚本)

时间:2018-03-27 20:55:16      阅读:236      评论:0      收藏:0      [点我收藏+]

标签:new   code   字符   col   bsp   eth   binding   访问   err   

1 用.NET提供的类动态编译代码字符串,生成DLL存于内存中,加载到程序域

2 用反射的方式调用这个DLL

将要被编译和执行的代码读入并以字符串方式保存
声明CSharpCodeProvider对象实例
调用CSharpCodeProvider实例的CompileAssemblyFromSource方法编译
用反射生成被生成对象的实例(Assembly.CreateInstance)
调用其方法

https://blog.csdn.net/clb929/article/details/51385399

 

 

应用:

1 获取编码字符串

   string strSourceCode = System.IO.File.ReadAllText("./TextFile1.txt");

2 创建代码生成/编译器访问实例

   CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider();

  CompilerParameters objCompilerParameters = new CompilerParameters();

  //程序集的引用(程序集路径)
  objCompilerParameters.ReferencedAssemblies.Add("System.dll");

  //是否需要将生成的文件(dll)放入内存

  objCompilerParameters.GenerateInMemory = true;
  CompilerResults cr = objCSharpCodePrivoder.CompileAssemblyFromSource(objCompilerParameters, strSourceCode);

3 通过反射调用刚才加载到内存的库,调用其方法

  Assembly objAssembly = cr.CompiledAssembly;

  //命名空间.类名称
  object objClass = objAssembly.CreateInstance("DyTest.Class1");

  object[] objCodeParms = new object[1];
  objCodeParms[0] = "Allan.";

  //调用方法

  string strResult = (string)objClass.GetType().InvokeMember("Go", BindingFlags.InvokeMethod, null, objClass, objCodeParms);

  

.Net 动态编译(c# 脚本)

标签:new   code   字符   col   bsp   eth   binding   访问   err   

原文地址:https://www.cnblogs.com/swobble/p/8659358.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!