我正在使用CSharpCompilation
该类来编译SyntaxTree
根是类声明的位置.我向构造函数传递一个CSharpCompilationOptions
包含我的using语句的对象.
我的理解是语法树将使用我传递的任何using语句的上下文进行编译.但是当试图访问一个'usings'中定义的类时,我传递给options对象,我得到一个错误,说它在当前上下文中不存在.
我显然做错了什么.有人知道传递给CSharpCompilationOptions
班级时的使用清单是什么?
这是代码:
public static void TestMethod() { string source = @"public class Test { public static void TestMethod() { string str = Directory.GetCurrentDirectory(); } }"; SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(source); Listusings = new List () { "System.IO", "System" }; List references = new List () { new MetadataFileReference(typeof(object).Assembly.Location), }; //adding the usings this way also produces the same error CompilationUnitSyntax root = (CompilationUnitSyntax)syntaxTree.GetRoot(); root = root.AddUsings(usings.Select(u => SyntaxFactory.UsingDirective(SyntaxFactory.IdentifierName(u))).ToArray()); syntaxTree = CSharpSyntaxTree.Create(root); CSharpCompilationOptions options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, usings: usings); CSharpCompilation compilation = CSharpCompilation.Create("output", new[] { syntaxTree }, references, options); using (MemoryStream stream = new MemoryStream()) { EmitResult result = compilation.Emit(stream); if (result.Success) { } } }
Kevin Pilch.. 7
因此,事实证明,CSharpCompilationOptions.Usings
编译脚本文件时只在编译器中检查过.如果您浏览引用,它最终会在此处使用,在if (inScript)
检查中.
我们可能需要更好地记录.
因此,事实证明,CSharpCompilationOptions.Usings
编译脚本文件时只在编译器中检查过.如果您浏览引用,它最终会在此处使用,在if (inScript)
检查中.
我们可能需要更好地记录.