Getting the type of an abstract class from which the class is derived

In .NET, using the GetType function returns the type of a specific object class. The problem is that I don’t know what type will be before execution, but I know from which abstract class its derivatives are (I use abstract factories to create the corresponding class).

How can I get the actual type of an abstract class? Is it possible?

+3
source share
2 answers

Type.BaseTypewill tell you the type from which the current type is inferred. You can recursively call Type.BaseTypeup .Type.IsAbstract true

static class TypeExtensions {
    public static Type GetFirstAbstractBaseType(this Type type) {
        if (type == null) {
            throw new ArgumentNullException("type");
        }
        Type baseType = type.BaseType;
        if (baseType == null || baseType.IsAbstract) {
            return baseType;
        }
        return baseType.GetFirstAbstractBaseType();
    }

Using:

Type abstractBase = typeof(Derived).GetFirstAbstractBaseType();
+12
source

, BaseType Type. , .

0

Source: https://habr.com/ru/post/1730897/


All Articles