所以我遇到了这个问题。
我正在尝试在内存中编译代码并通过搜索语法树添加命名空间引用,因此我不会手动添加它们。试图模拟 Visual Studio 可能是如何做到的。
我在编译部门有点不知所措。即使我在阅读语法树时添加对 System 的元数据引用,它也找不到 System.Console。
关键是我希望它自己包含程序集,我不想添加“MetadataReference.CreateFromFile(....,”System.Console”)。
我解释了下面的代码,以便清楚发生了什么。
class App
{
static void Main(string[] args)
{
//creating the syntax tree for the program
SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@"
namespace ns{
using System;
public class App{
public static void Main(string[] args){
Console.Write(""dada"");
}
}
}");
//creating options that tell the compiler to output a console application
var options = new CSharpCompilationOptions(
OutputKind.ConsoleApplication,
optimizationLevel: OptimizationLevel.Debug,
allowUnsafe: true);
//creating the compilation
var compilation = CSharpCompilation.Create(Path.GetRandomFileName(), options: options);
//adding the syntax tree …Run Code Online (Sandbox Code Playgroud)