在C#中动态编译和执行代码

见过不少人、经过不少事、也吃过不少苦,感悟世事无常、人心多变,靠着回忆将往事串珠成链,聊聊感情、谈谈发展,我慢慢写、你一点一点看......

public static void CompileAndExecute(string code)
{
    // 创建语法树
    SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code);
    // 设置编译选项
    string assemblyName = Path.GetRandomFileName();
    // 自动加载所有程序集引用
    var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic).Select(a => MetadataReference.CreateFromFile(a.Location)).ToList();
    CSharpCompilation compilation = CSharpCompilation.Create(
        assemblyName,
        syntaxTrees: new[] { syntaxTree },
        references: assemblies,
        options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
    // 编译代码
    using (var ms = new MemoryStream())
    {
        EmitResult result = compilation.Emit(ms);
        if (!result.Success)
        {
            Console.WriteLine("编译失败:");
            foreach (Diagnostic diagnostic in result.Diagnostics.Where(diag => diag.IsWarningAsError || diag.Severity == DiagnosticSeverity.Error))
            {
                Console.WriteLine($"{diagnostic.Id}: {diagnostic.GetMessage()}");
            }
        }
        else
        {
            ms.Seek(0, SeekOrigin.Begin);
            Assembly assembly = AssemblyLoadContext.Default.LoadFromStream(ms);
            MethodInfo method = assembly.GetType("Program").GetMethod("Main");
            method.Invoke(null, new object[] { new string[] { } });
        }
    }
}

调用例子:

string code = @"
     using System;
     public class Program
     {
         public static void Main(string[] args)
         {
             Console.WriteLine(1);
         }
     }
 ";

     CompileAndExecute(code);

关注我,不失联。有啥问题请留言。

感情恋爱合集https://blog.csdn.net/forever8341/category_12863789.html

职业发展故事https://blog.csdn.net/forever8341/category_12863790.html

常用代码片段https://blog.csdn.net/forever8341/category_12863793.html

程序开发教程https://blog.csdn.net/forever8341/category_12863792.html

自我备考经验 https://blog.csdn.net/forever8341/category_12863791.html

高阶高效代码https://blog.csdn.net/forever8341/category_12873345.html

金融语言解析https://blog.csdn.net/forever8341/category_12877262.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我曾经是个程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值