通过DTE按类型名称查找ProjectItem [英] Finding a ProjectItem by type name via DTE

查看:109
本文介绍了通过DTE按类型名称查找ProjectItem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出类型名称,是否可以使用DTE查找该类型所在的ProjectItem? Navigate To...对话框在Visual Studio 2010中的工作原理类似.

Given a type name, is it possible to use DTE to find the ProjectItem that the type is located in? Something similar to how the Navigate To... dialog works in Visual Studio 2010.

我能找到的最接近的是 Solution.FindProjectItem ,但这需要一个文件名.

The closest I could find is Solution.FindProjectItem, but that takes in a file name.

谢谢!

推荐答案

我一直在尝试做类似的事情,并提出了以下内容,它们仅搜索名称空间和类,直到找到您所需要的名称和类为止.寻找.

I've been trying to do something similar, and have come up with the following, which simply searches through namespaces and classes until it hits the one you're looking for.

尽管在遇到部分类时它只会返回第一个匹配项,但它似乎在大多数情况下都可以工作,并且由于它是文件的模型,因此只包含该文件中的成员.仍在弄清楚该怎么办.

It seems to work in most cases although when encountering a partial class it will only return the first hit, and as it's a model of the file it will only have the members contained in that file. Still figuring out what to do about that.

这来自T4模板,并且正在使用T4 Toolkit(这是TransformationContext的来源),因此,如果您不使用它,只需持有一个项目元素,然后将Project.CodeModel.CodeElements传递给递归FindClass方法.

This comes from a T4 template and is using T4 Toolkit (which is where TransformationContext comes from) so if you're not using that, just get a hold of a project element and pass Project.CodeModel.CodeElements to the recursive FindClass method.

用法示例为FindClass("MyCompany.DataClass");

Example usage would be FindClass("MyCompany.DataClass");

private CodeClass FindClass(string className)
{   
    return FindClass(TransformationContext.Project.CodeModel.CodeElements, className);
}

private CodeClass FindClass(CodeElements elements, string className)
{
    foreach (CodeElement element in elements)
    {       
        if(element is CodeNamespace || element is CodeClass)
        {
            CodeClass c = element as CodeClass;
            if (c != null && c.Access == vsCMAccess.vsCMAccessPublic)
            {
                if(c.FullName == className)
                    return c;

                CodeClass subClass = FindClass(c.Members, className);
                if(subClass!= null)
                    return subClass;
            }

            CodeNamespace ns = element as CodeNamespace;
            if(ns != null)
            {
                CodeClass cc = FindClass(ns.Members, className);
                if(cc != null)
                    return cc;
            }
        }
    }
    return null;
}

这篇关于通过DTE按类型名称查找ProjectItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆