这篇文章主要介绍“编译C#代码的应用方法是什么”,在日常操作中,相信很多人在编译C#代码的应用方法是什么问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”编译C#代码的应用方法是什么”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
编译C#代码应用场景:
还没想出来会用到哪里。动态的代码由谁来写?普通用户我想有一定的困难。特别是有了像 IronPython 这样更容易使用的动态嵌入脚本。
1) 像 LINQPad 这样的辅助开发工具
2) 实现脚本引擎?
3) 探讨...
主要使用命名空间 Microsoft.CSharp 编译C#代码,然后使用 CodeDom 和 反射调用,我这里写了一个测试工具,看代码:
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; // 用于反射调用 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) { // 编译参数 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) { // 反射调用 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; } } }
作为演示,例子简单的规定类名必须是MyClass,必须有一个方法返回 string 类型的 GetResult 方法。
到此,关于“编译C#代码的应用方法是什么”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。