Retrieve all Types with Roslyn within a solution

元气小坏坏 提交于 2019-12-06 03:38:06
Tamas

For a given compilation you can reach all available types through Compilation.GlobalNamespace by iterating over all GetTypeMembers() and GetNamespaceMembers() recursively. This is not giving you all the types in the solution, but all types that are available from the current compilation (project) through all its references.

In order not to reinvent the wheel, it is:

IEnumerable<INamedTypeSymbol> GetAllTypes(Compilation compilation) =>
    GetAllTypes(compilation.GlobalNamespace);

IEnumerable<INamedTypeSymbol> GetAllTypes(INamespaceSymbol @namespace)
{
    foreach (var type in @namespace.GetTypeMembers())
        foreach (var nestedType in GetNestedTypes(type))
            yield return nestedType;

    foreach (var nestedNamespace in @namespace.GetNamespaceMembers())
        foreach (var type in GetAllTypes(nestedNamespace))
            yield return type;
}

IEnumerable<INamedTypeSymbol> GetNestedTypes(INamedTypeSymbol type)
{
    yield return type;
    foreach (var nestedType in type.GetTypeMembers()
        .SelectMany(nestedType => GetNestedTypes(nestedType)))
        yield return nestedType;
}
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);
    }
}

Once you can access the solution, it is:

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));
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!