gpt4 book ai didi

c# - Roslyn - CSharpCompilation

转载 作者:可可西里 更新时间:2023-11-01 09:10:54 27 4
gpt4 key购买 nike

我正在使用 CSharpCompilation 类来编译 SyntaxTree,其中根是一个类声明。我向构造函数传递了一个包含我的 using 语句的 CSharpCompilationOptions 对象。

我的理解是语法树将使用我通过的任何 using 语句的上下文进行编译。但是,当尝试访问在我传递给选项对象的“使用”之一中定义的类时,我收到一条错误消息,指出它在当前上下文中不存在。

我显然做错了什么。有人知道传递给 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)
{
}
}
}

最佳答案

因此,事实证明 CSharpCompilationOptions.Usings 仅在编译脚本文件时在编译器中进行过检查。如果您跟踪引用资料,它最终会被使用 here , 在 if (inScript) 检查中。

我们可能需要更好地记录这一点。

关于c# - Roslyn - CSharpCompilation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24658381/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com