C#动态编译

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.CodeDom.Compiler; using Microsoft.CSharp; using System.Reflection; using System.IO; using System.Diagnostics; namespace WindowsFormsApplication18 { public partial class Form2 : Form { private BI_Log _LogEnt = new BI_Log(); public Form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { _LogEnt.LogType = "错误"; _LogEnt.Priority = 4; //MessageBox.Show("确定启动吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); var sw = new Stopwatch(); sw.Start(); Test(); sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); } #region private void Test() { var code = @" using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.CodeDom.Compiler; using Microsoft.CSharp; using System.Reflection; using System.IO; using WindowsFormsApplication18; public class Abc { public bool Get(BI_Log ent) { return ent.Priority>3; } } "; string exePath = Assembly.GetExecutingAssembly().Location; string exeDir = Path.GetDirectoryName(exePath); AssemblyName[] assemRefs = Assembly.GetExecutingAssembly().GetReferencedAssemblies(); List<string> references = new List<string>(); foreach (AssemblyName assemblyName in assemRefs) references.Add(assemblyName.Name + ".dll"); for (int i = 0; i < references.Count; i++) { string localName = Path.Combine(exeDir, references[i]); if (File.Exists(localName)) references[i] = localName; } references.Add(exePath); //CompilerParameters compiler_parameters = new CompilerParameters(references.ToArray()); var options = new CompilerParameters(references.ToArray()); options.GenerateExecutable = false; options.GenerateInMemory = true; var provider = new CSharpCodeProvider(); var compile = provider.CompileAssemblyFromSource(options, code); var type = compile.CompiledAssembly.GetType("Abc"); var abc = Activator.CreateInstance(type); var method = type.GetMethod("Get"); var objs = new object[] { _LogEnt}; var result = method.Invoke(abc, objs); Console.WriteLine(result); //输出:abc } #endregion } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
2021-04-15 分分钟做一个C#版的RPC,萌新可以来瞧瞧
2013-04-15 使用uPnP在路由器上映射端口
2010-04-15 SubSonic中RecordBase<T>.Load(IDataReader dataReader)与LoadAndCloseReader(IDataReader dataReader)的使用区别
2009-04-15 Cookie概要