Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
218 views
in Technique[技术] by (71.8m points)

c# - Finding all class declarations than inherit from another with Roslyn

I have a CSharpCompilation instance containing an array of SyntaxTrees and I am trying to find all the class declarations that inherit from a class

e.g

// Not in syntax tree but referenced in project
public class Base{}

// In syntax tree, how to find all such classes?
public class MyClass : Base {}

I've tried a few things but am a bit confused with all the options and can't seem to find the right way to do this.

I've tried to get the symbols but this doesn't work for inherited types

SyntaxTree[] trees = context.CSharpCompilation.SyntaxTrees;
IEnumerable<ISymbol> symbols = context.CSharpCompilation.GetSymbolsWithName(x => x == typeof(Base).Name, SymbolFilter.Type);

Quite new to Roslyn and would be most grateful for any suggestions or pointers for how to achieve this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First you'll need to get the symbol for Base. If this is a particular type you know about in advance, you can use Compilation.GetTypeByMetadataName for this. That link will also show you over 100 examples of that method in use.

From there, it depends on what you're trying to do. If you're doing this from inside an analyzer (which I suspect from the "context.CSharpCompilation" in your code), and you're trying to identify and then check some property of these derived types, you could use RegisterSymbolAction for SymbolKind.NamedType, and then check each type's BaseType (possibly recursively, depending on what you're trying to accomplish) to see if you find the type discovered by GetTypeByMetadataName above.

If you're doing solution-wide analysis outside the context of an analyzer, then there's a helper for this in the Roslyn codebase, but it's internal. There's an existing request to make ITypeSymbolExtensions public, so I've mentioned this thread in that request and suggested expanding it to include INamedTypeSymbolExtensions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...