简单介绍编译C#代码

编译C#代码应用场景:
还没想出来会用到哪里。动态的代码由谁来写?普通用户我想有一定的困难。特别是有了像 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. namespace CodeDomLearn  
  10. {  
  11. public partial class Form1 : Form  
  12. {  
  13. public Form1() {  
  14. InitializeComponent();  
  15.  
  16. }  
  17.  
  18. private void button1_Click(object sender, EventArgs e) {  
  19. CodeCompiler.Compile(new string[] { }, textBox1.Text, "");  
  20. listBox1.Items.Clear();  
  21. foreach (string s in CodeCompiler.ErrorMessage) {  
  22. listBox1.Items.Add(s);  
  23. }  
  24. listBox1.Items.Add(CodeCompiler.Message);  
  25. }  
  26. }  
  27.  
  28. static class CodeCompiler {  
  29. static public string Message;  
  30. static public List ErrorMessage = new List();  
  31.  
  32. public static bool Compile
    (string[] references, string source, string outputfile) {  
  33. // 编译参数    
  34. CompilerParameters param = new CompilerParameters
    (references, outputfile, true);  
  35. param.TreatWarningsAsErrors = false;  
  36. param.GenerateExecutable = false;  
  37. param.IncludeDebugInformation = true;  
  38.  
  39. // 编译    
  40. CSharpCodeProvider provider = new CSharpCodeProvider();  
  41. CompilerResults result = provider.CompileAssemblyFromSource
    (param, new string[] { source });  
  42.  
  43. Message = "";  
  44. ErrorMessage.Clear();  
  45. if (!result.Errors.HasErrors) { // 反射调用    
  46. Type t = result.CompiledAssembly.GetType("MyClass");  
  47. if (t != null) {  
  48. object o = result.CompiledAssembly.CreateInstance("MyClass");  
  49. Message = (string)t.InvokeMember("GetResult", BindingFlags.Instance | 
    BindingFlags.InvokeMethod | BindingFlags.Public, null, o, null);  
  50. }  
  51. return true;  
  52. }  
  53.  
  54. foreach (CompilerError error in result.Errors) {  // 列出编译错误  
  55. if (error.IsWarning) continue;  
  56. ErrorMessage.Add("Error(" + error.ErrorNumber + ") - " + error.ErrorText + 
    "\t\tLine:" + error.Line.ToString() + "  Column:"+error.Column.ToString());  
  57. }  
  58. return false;  
  59. }  
  60.  
  61. }  

作为演示,例子简单的规定类名必须是MyClass,必须有一个方法返回 string 类型的 GetResult 方法。以上介绍编译C#代码

本文标题:简单介绍编译C#代码
分享链接:http://www.csdahua.cn/qtweb/news5/344905.html

网站建设、网络推广公司-快上网,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 快上网