c# 动态编译CS文件

 执行程序

using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string sourceCode = File.ReadAllText(@text.cs文件路径, Encoding.UTF8);
            MessageBox.Show(sourceCode);
            // 创建编译器选项
            CompilerParameters compilerParams = new CompilerParameters();
            compilerParams.GenerateInMemory = true; // 将程序集生成到内存中
            compilerParams.GenerateExecutable = false; // 生成的程序集为类库

            // 添加需要引用的程序集,例如System.dll
            compilerParams.ReferencedAssemblies.Add("System.dll");
            compilerParams.ReferencedAssemblies.Add("System.Windows.Forms.dll");

            // 创建C#编译器
            CSharpCodeProvider provider = new CSharpCodeProvider();

            // 编译C#代码
            CompilerResults compilerResults = provider.CompileAssemblyFromSource(compilerParams, sourceCode);

            // 检查编译是否成功
            if (compilerResults.Errors.HasErrors)
            {
                // 输出编译错误信息
                foreach (CompilerError error in compilerResults.Errors)
                {
                    //Console.WriteLine("Error: {0}", error.ErrorText);
                    MessageBox.Show( error.ErrorText);
                }
            }
            else
            {
                // 获取编译后的程序集
                Assembly assembly = compilerResults.CompiledAssembly;

                // 创建动态类的实例并调用其中的方法
                dynamic dynamicClass = assembly.CreateInstance("Program");//test.cs的类名
                var ret = dynamicClass.PrintOut(99);//test.cs的函数和参数
                MessageBox.Show(ret);//test.cs的PrintOut函数返回值
            }
        }
    }
}

 test.cs文件

//代码模板案例
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;


//Here is class place
//===Class===
public class Program
{

    /// <summary>
    /// 应用程序的主入口点。
    /// </summary>
    public void Main(string show)
    {
        MessageBox.Show(show);
        //Here is code body place
        //===Code===
    }
    public string PrintOut(int tot)
    {
        string ret="";
        for(int i=0;i<=tot;i++)
        {
            ret+=i.ToString()+":";
        }
        return ret;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值