Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

envdte - Finding a ProjectItem by type name via DTE

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.

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

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...