簡單介紹編譯C#代碼
作者:佚名
本文介紹編譯C#代碼,主要使用命名空間 Microsoft.CSharp 編譯C#代碼,然后使用 CodeDom 和 反射調(diào)用,我這里寫了一個測試工具
編譯C#代碼應(yīng)用場景:
還沒想出來會用到哪里。動態(tài)的代碼由誰來寫?普通用戶我想有一定的困難。特別是有了像 IronPython 這樣更容易使用的動態(tài)嵌入腳本。
1) 像 LINQPad 這樣的輔助開發(fā)工具
2) 實現(xiàn)腳本引擎?
3) 探討...
主要使用命名空間 Microsoft.CSharp 編譯C#代碼,然后使用 CodeDom 和 反射調(diào)用,我這里寫了一個測試工具,看代碼:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Drawing;
- using System.Windows.Forms;
- using System.CodeDom.Compiler;
- using Microsoft.CSharp; // 用于編譯C#代碼
- using System.Reflection; // 用于反射調(diào)用
- namespace CodeDomLearn
- {
- public partial class Form1 : Form
- {
- public Form1() {
- InitializeComponent();
- }
- private void button1_Click(object sender, EventArgs e) {
- CodeCompiler.Compile(new string[] { }, textBox1.Text, "");
- listBox1.Items.Clear();
- foreach (string s in CodeCompiler.ErrorMessage) {
- listBox1.Items.Add(s);
- }
- listBox1.Items.Add(CodeCompiler.Message);
- }
- }
- static class CodeCompiler {
- static public string Message;
- static public List<string> ErrorMessage = new List<string>();
- public static bool Compile
(string[] references, string source, string outputfile) {- // 編譯參數(shù)
- CompilerParameters param = new CompilerParameters
(references, outputfile, true);- param.TreatWarningsAsErrors = false;
- param.GenerateExecutable = false;
- param.IncludeDebugInformation = true;
- // 編譯
- CSharpCodeProvider provider = new CSharpCodeProvider();
- CompilerResults result = provider.CompileAssemblyFromSource
(param, new string[] { source });- Message = "";
- ErrorMessage.Clear();
- if (!result.Errors.HasErrors) { // 反射調(diào)用
- Type t = result.CompiledAssembly.GetType("MyClass");
- if (t != null) {
- object o = result.CompiledAssembly.CreateInstance("MyClass");
- Message = (string)t.InvokeMember("GetResult", BindingFlags.Instance |
BindingFlags.InvokeMethod | BindingFlags.Public, null, o, null);- }
- return true;
- }
- foreach (CompilerError error in result.Errors) { // 列出編譯錯誤
- if (error.IsWarning) continue;
- ErrorMessage.Add("Error(" + error.ErrorNumber + ") - " + error.ErrorText +
"\t\tLine:" + error.Line.ToString() + " Column:"+error.Column.ToString());- }
- return false;
- }
- }
- }
作為演示,例子簡單的規(guī)定類名必須是MyClass,必須有一個方法返回 string 類型的 GetResult 方法。以上介紹編譯C#代碼
【編輯推薦】
責(zé)任編輯:佚名
來源:
Infoq