Finding all class declarations than inherit from another with Roslyn

前端 未结 3 1200
终归单人心
终归单人心 2020-12-10 15:45

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

3条回答
  •  失恋的感觉
    2020-12-10 16:32

    So I came up with the following which will recursively check all classes for the inherited type

    public class BaseClassRewriter : CSharpSyntaxRewriter
    {
        private readonly SemanticModel _model;
    
        public BaseClassRewriter(SemanticModel model)
        {
            _model = model;
        }
    
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            var symbol = _model.GetDeclaredSymbol(node);
            if (InheritsFrom(symbol))
            {
                // hit!
            }
        }
    
        private bool InheritsFrom(INamedTypeSymbol symbol)
        {
            while (true)
            {
                if (symbol.ToString() == typeof(T).FullName)
                {
                    return true;
                }
                if (symbol.BaseType != null)
                {
                    symbol = symbol.BaseType;
                    continue;
                }
                break;
            }
            return false;
        }
    }
    

提交回复
热议问题