简体   繁体   中英

Get all types and interfaces a class inherits from and implements in C#

I saw this question which is similar to mine:

How to find all the types in an Assembly that Inherit from a Specific Type C#

However, what if my class implements multiple interfaces as well:

class MyClass: MyBaseClass, IMyInterface1, IMyInterface2

Can I somehow get an array of all the stuff MyClass implements, and not just going one by one?

对于接口,您可以调用Type.GetInterfaces()

If you are interested in all the base types plus interfaces you can use:

static Type[] BaseTypesAndInterfaces(Type type) 
{
    var lst = new List<Type>(type.GetInterfaces());

    while (type.BaseType != null) 
    {
        lst.Add(type.BaseType);
        type = type.BaseType;
    }

    return lst.ToArray();
}

Use it like:

var x = BaseTypesAndInterfaces(typeof(List<MyClass>));

It's even possible to make it generic-based

static Type[] BaseTypesAndInterfaces<T>() 
{
    Type type = typeof(T);

    var lst = new List<Type>(type.GetInterfaces());

    while (type.BaseType != null) 
    {
        lst.Add(type.BaseType);
        type = type.BaseType;
    }

    return lst.ToArray();
}

and

var x = BaseTypesAndInterfaces<MyClass>();

but it's probably less interesting (because normally you "discover" MyClass at runtime, so you can't easily use generic methods with it)

If you want to combine interfaces with the base type into a single array, you can do this:

var t = typeof(MyClass);
var allYourBase = new[] {t.BaseType}.Concat(t.GetInterfaces()).ToArray();

Note that your array would contain all bases, including System.Object . This will not work for System.Object , because its base type is null .

You could get all in one go using something like:

var allInheritance = type.GetInterfaces().Union(new[] { type.BaseType});

Live example: http://rextester.com/QQVFN51007

Here's the extension method I use:

public static IEnumerable<Type> EnumInheritance(this Type type)
{
    while (type.BaseType != null)
        yield return type = type.BaseType;
    foreach (var i in type.GetInterfaces())
        yield return i;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM