How to get ancestors of a class in Coderush?
I was trying to get all ancestors (Classes and Interfaces) of a Class to a list.
I tried this code but did not work.
public static List<Class> AncestorList;
public static void GetAncestorList(Class curClass)
{
if(curClass.PrimaryAncestorType!=null)
{
Class primaryAncestor = curClass.PrimaryAncestorType.Resolve(new SourceTreeResolver()) as Class;
if(primaryAncestor !=null)
{
AncestorList.Add(primaryAncestor);//Add primary ancestor to the list.
GetAncestorList(primaryAncestor);//find the ancestors of the primary ancestor.
}
foreach (TypeReferenceExpression typ1 in curClass.SecondaryAncestorTypes )
{
Class secAncestor = typ1.Resolve(new SourceTreeResolver()) as Class;
if(secAncestor !=null)
{
AncestorList.Add(secAncestor);//Add secondary ancestor to the list.
GetAncestorList(secAncestor);//find ancestors of secondary ancestor.
}
}
}
In this part of code I tried to collect all the classes and interfaces into AncestorList. But when I tried to find number classes in the list it showed 0. The test project had fe开发者_StackOverflow中文版w parent classes and interfaces. Please help to find the error.
I made a Call to the GetAncestorList function in the following way.
AncestorList=new List<Class>();
GetAncestorList(currentClass);
Thanks in Advance,
Vinod
There's a better method to get all ancestors of a class:
ITypeElement[] ancestors = curClass.GetBaseTypes();
or this one:
ITypeElement[] ancestors = CodeRush.Source.GetAllBaseTypes(curClass);
But these calls will return instances of ITypeElement type - it depends on how you are going to use instances of ancestors. If you'd like to convert ITypeElement into a Class instance, use the following code:
foreach (ITypeElement ancestor in ancestors)
{
Class classInstance = ancestor.ToLanguageElement() as Class;
if (classInstance != null)
AncestorList.Add(classInstance);
}
精彩评论