Check if a class is derived from a generic class

前端 未结 16 1574
太阳男子
太阳男子 2020-11-22 09:57

I have a generic class in my project with derived classes.

public class GenericClass : GenericInterface
{
}

public class Test : GenericCla         


        
16条回答
  •  天涯浪人
    2020-11-22 10:16

    It might be overkill but I use extension methods like the following. They check interfaces as well as subclasses. It can also return the type that has the specified generic definition.

    E.g. for the example in the question it can test against generic interface as well as generic class. The returned type can be used with GetGenericArguments to determine that the generic argument type is "SomeType".

    /// 
    /// Checks whether this type has the specified definition in its ancestry.
    ///    
    public static bool HasGenericDefinition(this Type type, Type definition)
    {
        return GetTypeWithGenericDefinition(type, definition) != null;
    }
    
    /// 
    /// Returns the actual type implementing the specified definition from the
    /// ancestry of the type, if available. Else, null.
    /// 
    public static Type GetTypeWithGenericDefinition(this Type type, Type definition)
    {
        if (type == null)
            throw new ArgumentNullException("type");
        if (definition == null)
            throw new ArgumentNullException("definition");
        if (!definition.IsGenericTypeDefinition)
            throw new ArgumentException(
                "The definition needs to be a GenericTypeDefinition", "definition");
    
        if (definition.IsInterface)
            foreach (var interfaceType in type.GetInterfaces())
                if (interfaceType.IsGenericType
                    && interfaceType.GetGenericTypeDefinition() == definition)
                    return interfaceType;
    
        for (Type t = type; t != null; t = t.BaseType)
            if (t.IsGenericType && t.GetGenericTypeDefinition() == definition)
                return t;
    
        return null;
    }
    

提交回复
热议问题