Accessing all the methods and classes for VS Exten

2019-08-20 07:26发布

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条回答
对你真心纯属浪费
2楼-- · 2019-08-20 07:36
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.

查看更多
登录 后发表回答