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);
}
这就是我开始搜索代码元素的方式。下面显示了这种递归方法,它为我搜索整个活动文档并根据我的要求获取元素列表。
对于类的搜索:
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);
}
}
对于搜索方法:
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);
}
}
我通过GitHub找到了这个解决方案,它显示了同样的逻辑。