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)

c# - Find all parent types (both base classes and interfaces)

I want to be able to find all parent types (base classes and interfaces) for a specific type.

EG if i have

class A : B, C { }
class B : D { }
interface C : E { }
class D { }
interface E { }

i want to see that A is B C D and E and Object

Whats the best way to do this? is there a reflection method to do this or do i need to make myself something.

====EDIT====

So something like this?

public static IEnumerable<Type> ParentTypes(this Type type)
    {
        foreach (Type i in type.GetInterfaces())
        {
            yield return i;
            foreach (Type t in i.ParentTypes())
            {
                yield return t;
            }
        }

        if (type.BaseType != null)
        {
            yield return type.BaseType;
            foreach (Type b in type.BaseType.ParentTypes())
            {
                yield return b;
            }
        }
    }

I was kinda hoping i didn't have to do it myself but oh well.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

More general solution:

public static bool InheritsFrom(this Type type, Type baseType)
{
    // null does not have base type
    if (type == null)
    {
        return false;
    }

    // only interface or object can have null base type
    if (baseType == null)
    {
        return type.IsInterface || type == typeof(object);
    }

    // check implemented interfaces
    if (baseType.IsInterface)
    {
        return type.GetInterfaces().Contains(baseType);
    }

    // check all base types
    var currentType = type;
    while (currentType != null)
    {
        if (currentType.BaseType == baseType)
        {
            return true;
        }

        currentType = currentType.BaseType;
    }

    return false;
}

Or to actually get all parent types:

public static IEnumerable<Type> GetParentTypes(this Type type)
{
    // is there any base type?
    if (type == null)
    {
        yield break;
    }

    // return all implemented or inherited interfaces
    foreach (var i in type.GetInterfaces())
    {
        yield return i;
    }

    // return all inherited types
    var currentBaseType = type.BaseType;
    while (currentBaseType != null)
    {
        yield return currentBaseType;
        currentBaseType= currentBaseType.BaseType;
    }
}

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

...