如何列出解决方案中从特定类型继承的所有类型?

How to list all types inherited from a specific type in a solution?

我正在尝试获取 VS 解决方案中从特定类型继承的所有类型的列表。 下面的代码似乎列出了 vs 解决方案中的所有 类,但不确定如何通过继承过滤它们:

var workspace = MSBuildWorkspace.Create();
CancellationToken cancellationToken = default(CancellationToken);
var solution = await workspace.OpenSolutionAsync(path, cancellationToken);
Project project = solution.Projects.First(p => p.Name == "WebApplication1");
var compilation = await project.GetCompilationAsync();

var classes = compilation.
    GlobalNamespace.
    GetNamespaceMembers().
    SelectMany(x => x.GetMembers());

您正在寻找 SymbolFinder.FindDerivedClassesAsync()

使用您的示例,它看起来像:

var workspace = MSBuildWorkspace.Create();
CancellationToken cancellationToken = default(CancellationToken);
var solution = await workspace.OpenSolutionAsync(path, cancellationToken);

INamedTypeSymbol symbol = ... //Find the symbol for the type you're interested interested
var results = await SymbolFinder.FindDerivedClassesAsync(symbol, solution);

请注意,虽然此示例适用于 类,但 SymbolFinder 具有适用于各种场景的方法,包括查找接口的实现。