繁体   English   中英

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

[英]Programmatically compiling source code using Roslyn

所以我一直在尝试用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");

罗斯林对象是不可变的。

compilation.AddReferences()返回带有这些引用的新编译实例。
您正在忽略该新实例。

您需要在具有引用的编译实例上调用Emit()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM