所以我一直在尝试用 Roslyn 以编程方式编译一段代码。由于某些原因,我添加的引用并没有出现在 Compilation 类中。因此,当我在使用“AddReferences”后查看引用的程序集时,列表为空。因此,当我尝试发射时,我得到诊断中未定义的“对象”。谁能指出我的问题?
Microsoft.CodeAnalysis.SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(@"
public static class Program
{
public static void Main()
{
System.Console.WriteLine(""Hello"");
}
}
");
string autoreferences = @"mscorlib.dll,System.Core.dll";
List<string> usings = new List<string>();
string netAssembliesDirectory = Path.GetDirectoryName(typeof(object).Assembly.Location);
var refs = new List<string>();
foreach (string reference in autoreferences.Split(','))
refs.Add(netAssembliesDirectory + "\\" + reference);
CSharpCompilation compilation = CSharpCompilation.Create("ConsoleTest")
.WithOptions(
new CSharpCompilationOptions(OutputKind.ConsoleApplication).WithUsings("System"))
.AddSyntaxTrees(syntaxTree);
compilation.AddReferences(refs.Where(r => r != "").Select(r => MetadataReference.CreateFromFile(r)));
var er = compilation.Emit(@"C:\" + "ConsoleTest");