使用Roslyn以编程方式编译源代码

Far*_*ori 1 c# compilation roslyn roslyn-code-analysis

所以我一直在尝试用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");
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 5

Roslyn对象是不可变的.

compilation.AddReferences()返回带有这些引用的新编译实例.
你忽略了那个新实例.

您需要调用Emit()包含引用的编译实例.