我正在尝试使用Roslyn编译器SDK将某些修复程序应用于C#解决方案。我的计划是像这样遍历所有文件:
foreach (ProjectId projectId in originalSolution.ProjectIds)
{
Project project = newSolution.GetProject(projectId);
Console.WriteLine(project.Name);
foreach (DocumentId documentId in project.DocumentIds)
{
Document document = newSolution.GetDocument(documentId);
if (!document.SupportsSyntaxTree || !document.SupportsSemanticModel)
{
continue;
}
var mdl = await document.GetSemanticModelAsync();
var rw = new Rewriter(mdl);
var result = rw.Visit(mdl.SyntaxTree.GetRoot());
}
}
此代码基本上是从Roslyn示例复制而来的,似乎可以正常工作。但是,在Rewriter实现中,如下所示:
public class Rewriter: CSharpSyntaxRewriter
{
private readonly SemanticModel _mdl;
public Rewriter(SemanticModel mdl)
{
_mdl = mdl;
}
public override SyntaxNode VisitFieldDeclaration(FieldDeclarationSyntax node)
{
var info = _mdl.GetDeclaredSymbol(node);
// do stuff here...
return node;
}
GetDeclaredSymbol
方法返回null。谷歌搜索问题,我发现类似的问题,问题在于该文档未能成功编译。但是,情况并非如此:我检查了Compilation.GetDiagnostics()
和编译Compilation.References
,一切都井井有条。我在这里做什么错了?