Check if a class is derived from a generic class

前端 未结 16 1594
太阳男子
太阳男子 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:15

    This can all be done easily with linq. This will find any types that are a subclass of generic base class GenericBaseType.

        IEnumerable allTypes = Assembly.GetExecutingAssembly().GetTypes();
    
        IEnumerable mySubclasses = allTypes.Where(t => t.BaseType != null 
                                                                && t.BaseType.IsGenericType
                                                                && t.BaseType.GetGenericTypeDefinition() == typeof(GenericBaseType<,>));
    

提交回复
热议问题