Finding all not inheriting C# classes with Roslyn and changing to inheriting from base object (java-like)

天大地大妈咪最大 提交于 2019-12-03 21:39:47

ClassDeclarationSyntax has BaseList that contains Types. So you can retrieve information about base classes use these fields:

        foreach (var c in correctRoot.DescendantNodesAndSelf())
        {
            var classDeclaration = c as ClassDeclarationSyntax;
            if (classDeclaration == null)
            {
                continue;
            }
            if (classDeclaration.BaseList?.Types.Count > 0)
            {
                Console.WriteLine("This class has base class or it implements interfaces");
            }
            else
            {
                /*Add inherition*/
            }
        }

Unfortunately, you need extra logic to distinguish that your class has base class or it just implements interfaces. If you want to solve this you need to analyze base object(class/interface) using semantical model to get info about corresponding ISymbol or try to find declaration of these nodes in the syntax tree, if this declaration is defined in your projects/solutions.

Also if you want to add inheritation to class you need to set into BaseList a new created node using SyntaxFactory.SimpleBaseType(...) and SyntaxFactory.BaseList(...)

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