Accessing all the methods and classes for VS Exten

2019-08-20 06:55发布

问题:

I am developing an extension for visual studio with adornment. I have to put label above every class and methods in active document.

Now my problem is how can I get all the methods and classes? I searched for it but none of them shows the exact solution.

Thanks in advance!

回答1:

if(this._dte!=null && this._dte.ActiveDocument!=null)
        {
            List<CodeClass> foundClasses = new List<CodeClass>();
            List<CodeFunction> foundMethod = new List<CodeFunction>();
            CodeElements elementsInDocument = this._dte.ActiveDocument.ProjectItem.FileCodeModel.CodeElements;
            RecursiveClassSearch(this._dte.ActiveDocument.ProjectItem.FileCodeModel.CodeElements, foundClasses);
            RecursiveMethodSearch(this._dte.ActiveDocument.ProjectItem.FileCodeModel.CodeElements, foundMethod);
        }

This is how I started my search for code elements.This recursive methods are shown below that searches the whole active document for me and get me list of element as per my requirement.

For the searching of class:

 private static void RecursiveClassSearch(CodeElements elements, List<CodeClass> foundClasses)
    {
        foreach (CodeElement codeElement in elements)
        {
            if (codeElement is CodeClass)
            {
                foundClasses.Add(codeElement as CodeClass);
            }
            RecursiveClassSearch(codeElement.Children, foundClasses);
        }
    }

For searching methods:

public static void RecursiveMethodSearch(CodeElements elements, List<CodeFunction> foundMethod)
        {
            foreach (CodeElement codeElement in elements)
            {
                if(codeElement is CodeFunction)
                {
                    foundMethod.Add(codeElement as CodeFunction);
                }
                RecursiveMethodSearch(codeElement.Children, foundMethod);
            }
        }

I found this solution through GitHub which is showing this same logic.