Roslyn, how to get all Classes
This is how I visit all the classes in my solution.
class ClassVirtualizationVisitor : CSharpSyntaxRewriter
{
List<string> classes = new List<String>();
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
{
node = (ClassDeclarationSyntax) base.VisitClassDeclaration(node);
string className = node.Identifier.ValueText;
classes.Add(className); // save your visited classes
return node;
}
}
Now use the visited classes:
var classVisitor = new ClassVirtualizationVisitor();
classVisitor.Visit(semanticModel.SyntaxTree.GetRoot());
var classes = classVisitor.classes; // list of classes in your solution
This now is my working Code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.MSBuild;
using System.Threading.Tasks;
namespace Kardex.LC3xx.CreateApiDokumentation
{
//Patch to work with VS2013
// https://support.microsoft.com/en-us/kb/2971005
class Program
{
private static void Main(string[] args)
{
Run(args).Wait();
Console.ReadLine();
}
private async static Task Run(string[] args)
{
var path = Path.GetDirectoryName(typeof (Program).Assembly.Location);
var sln = Path.Combine(path, "xxx.sln");
var workspace = MSBuildWorkspace.Create();
var solution = await workspace.OpenSolutionAsync(sln);
Project project = solution.Projects.First(x => x.Name == "bbbb");
var compilation = await project.GetCompilationAsync();
foreach (var @class in compilation.GlobalNamespace.GetNamespaceMembers().SelectMany(x=>x.GetMembers()))
{
Console.WriteLine(@class.Name);
Console.WriteLine(@class.ContainingNamespace.Name);
}
var classVisitor = new ClassVirtualizationVisitor();
foreach (var syntaxTree in compilation.SyntaxTrees)
{
classVisitor.Visit(syntaxTree.GetRoot());
}
var classes = classVisitor.Classes;
}
class ClassVirtualizationVisitor : CSharpSyntaxRewriter
{
public ClassVirtualizationVisitor()
{
Classes = new List<ClassDeclarationSyntax>();
}
public List<ClassDeclarationSyntax> Classes { get; set; }
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
{
node = (ClassDeclarationSyntax)base.VisitClassDeclaration(node);
Classes.Add(node); // save your visited classes
return node;
}
}
}
}
Create a SymbolVisitor that overrides VisitNamedType
to process each type (which may not be a class).
Then, pass it to compilation.Assembly.Accept()
.