Question

I'm trying to iterate over all classes that inherit a specific base class. Most links i find reference to tangible's T4 Editor. Like this SO answer that almost does what I want

get-all-methods-that-are-decorated-with-a-%20specific-attribute-using-t4-envdte

Problem is I cant find the methods he is using like GetAllCodeElementsOfType

I am using this template enter image description here

Am I using the correct template?

Was it helpful?

Solution

Here are the helper methods I wrote to get all sub classes implementing a specific base class

public IEnumerable<CodeClass> GetSubClasses(string baseClass, Project project)
{
    var classes = VisualStudioHelper.CodeModel.GetAllCodeElementsOfType(project.CodeModel.CodeElements, EnvDTE.vsCMElement.vsCMElementClass, false);
    var subClasses = new List<CodeClass>();
    foreach (CodeClass @class in classes)
    {
        foreach (CodeClass @base in GetInheritance(@class))
        {
            if (@base.FullName == baseClass)
                subClasses.Add(@class);
        }

    }

    return subClasses;
}

public IEnumerable<CodeClass> GetInheritance(CodeClass @class)
{
    return GetInheritance(@class, new List<CodeClass>());
}

public IEnumerable<CodeClass> GetInheritance(CodeClass @class, List<CodeClass> collection)
{
    foreach (CodeClass @base in @class.Bases)
    {
        collection.Add(@base);
        GetInheritance(@base, collection);
    }

    return collection;
}

I will rewrite them with Linq, I found out that if you do .Cast<> on the untyped arrays you can use Linq so that will make the code a bit cleaner

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top