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

2311

被折叠的 条评论
为什么被折叠?



