有谁知道如何在解决方案中检索所有可用类型(语义)? 从几个项目中创建汇编很容易。
MSBuildWorkspace workspace = MSBuildWorkspace.Create();
var solution = await workspace.OpenSolutionAsync(solutionPath, cancellationToken);
var compilations = await Task.WhenAll(solution.Projects.Select(x => x.GetCompilationAsync(cancellationToken)));
对我来说,迭代所有ClassDeclarations是不够的,因为我想要所有类型以及它们之间的连接。
foreach (var tree in compilation.SyntaxTrees)
{
var source = tree.GetRoot(cancellationToken).DescendantNodes();
var classDeclarations = source.OfType<ClassDeclarationSyntax>();
}
答案 0 :(得分:4)
对于给定的编译,您可以通过递归迭代所有Compilation.GlobalNamespace
和GetTypeMembers()
,通过GetNamespaceMembers()
覆盖所有可用类型。这并没有为您提供解决方案中的所有类型,而是从当前编译(项目)到其所有引用可用的所有类型。
答案 1 :(得分:0)
List<ISymbol> ls = new List<ISymbol>();
foreach (Document d in p.Documents)
{
SemanticModel m = d.GetSemanticModelAsync().Result;
List<ClassDeclarationSyntax> lc = d.GetSyntaxRootAsync().Result.DescendantNodes().OfType<ClassDeclaractionSyntax>().ToList();
foreach ( var c in lc )
{
ISymbol s = m.GetDeclaredSymbol(c);
ls.Add(s);
}
}
答案 2 :(得分:0)
一旦您可以访问该解决方案,它就是:
IEnumerable<INamedTypeSymbol> types =
solution
.Projects
.SelectMany(project => project.Documents)
.Select(document =>
new
{
Model = document.GetSemanticModelAsync().Result,
Declarations = document.GetSyntaxRootAsync().Result
.DescendantNodes().OfType<TypeDeclarationSyntax>()
})
.SelectMany(pair =>
pair.Declarations.Select(declaration =>
pair.Model.GetDeclaredSymbol(declaration) as INamedTypeSymbol));