我正在使用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);
List<string> usings = new List<string>()
{
"System.IO", "System"
};
List<MetadataFileReference> references = new List<MetadataFileReference>()
{
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)
{
}
}
}
Run Code Online (Sandbox Code Playgroud)