频道直达 - 专题 - 新闻 - 技巧 - 组网 - 开发 - 安全 - web编程 - 图像 - 操作系统 - 数据库 - 教育 - 旅游 - 健康 - 时尚 - 驱动 - 软件 - 游戏 - 多媒体 - ERP - 讨论组

动态执行C#代码

来源:pcdog 作者:佚名 出处:巧巧读书 2008-02-18 进入讨论组

  写这篇笔记的理由是因为上篇g提高的工具LINQPad,见:
  想用LINQ思考吗?扔掉SQL查询分析器,Come on LINQPad!
  该工具的实现就有执行动态代码的应用。

  应用场景:
  还没想出来会用到哪里。动态的代码由谁来写?普通用户我想有一定的困难。
  特别是有了像 IronPython 这样更容易使用的动态嵌入脚本。

  1) 像 LINQPad 这样的辅助开发工具
  2) 实现脚本引擎?
  3) 探讨...

  主要使用命名空间 Microsoft.CSharp 编译C#代码,然后使用 CodeDom 和 反射调用,我这里写了一个测试工具,看代码:

1. using System; 2. using System.Collections.Generic; 3. using System.ComponentModel; 4. using System.Drawing; 5. using System.Windows.Forms; 6. using System.CodeDom.Compiler; 7. using Microsoft.CSharp; // 用于编译C#代码 8. using System.Reflection; // 用于反射调用 9. 10. namespace CodeDomLearn 11. { 12. public partial class Form1 : Form 13. { 14. public Form1() { 15. InitializeComponent(); 16. 17. } 18. 19. private void button1_Click(object sender, EventArgs e) { 20. CodeCompiler.Compile(new string[] { }, textBox1.Text, ""); 21. listBox1.Items.Clear(); 22. foreach (string s in CodeCompiler.ErrorMessage) { 23. listBox1.Items.Add(s); 24. } 25. listBox1.Items.Add(CodeCompiler.Message); 26. } 27. } 28. 29. static class CodeCompiler { 30. static public string Message; 31. static public List<string> ErrorMessage = new List<string>(); 32. 33. public static bool Compile(string[] references, string source, string outputfile) { 34. // 编译参数 35. CompilerParameters param = new CompilerParameters(references, outputfile, true); 36. param.TreatWarningsAsErrors = false; 37. param.GenerateExecutable = false; 38. param.IncludeDebugInformation = true; 39. 40. // 编译 41. CSharpCodeProvider provider = new CSharpCodeProvider(); 42. CompilerResults result = provider.CompileAssemblyFromSource(param, new string[] { source }); 43. 44. Message = ""; 45. ErrorMessage.Clear(); 46. if (!result.Errors.HasErrors) { // 反射调用 47. Type t = result.CompiledAssembly.GetType("MyClass"); 48. if (t != null) { 49. object o = result.CompiledAssembly.CreateInstance("MyClass"); 50. Message = (string)t.InvokeMember("GetResult", BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Public, null, o, null); 51. } 52. return true; 53. } 54. 55. foreach (CompilerError error in result.Errors) { // 列出编译错误 56. if (error.IsWarning) continue; 57. ErrorMessage.Add("Error(" + error.ErrorNumber + ") - " + error.ErrorText + "\t\tLine:" + error.Line.ToString() + " Column:"+error.Column.ToString()); 58. } 59. return false; 60. } 61. 62. } 63. }


  作为演示,例子简单的规定类名必须是MyClass,必须有一个方法返回 string 类型的 GetResult 方法。这是执行效果图:

动态执行C#代码

浏览地址: http://www.qqread.com/csharp/a397050.html进入讨论组讨论。
收藏此文】【 】【打印】【关闭
相关图文阅读
频道图文推荐
健 康 咨 询
时 尚 咨 询
巧巧读书宗旨
相关专题
讨论组问题推荐
站内各频道最新更新文档
站内最新制作专题
热门关键字导读
Photoshop教 程照片处理 照片制作 PS快捷键 抠图
计 算 机 故 障XP系统修复
艺 术 与 设 计设计 流媒体 设计欣赏 边框
计 算 机 安 全ARP
站内频道文章精选
巧巧电脑频道编辑信箱  告诉我们您想看的专题或文章