Check if a class is derived from a generic class

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

    JaredPar,

    This did not work for me if I pass typeof(type<>) as toCheck. Here's what I changed.

    static bool IsSubclassOfRawGeneric(Type generic, Type toCheck) {
        while (toCheck != typeof(object)) {
            var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
              if (cur.IsGenericType && generic.GetGenericTypeDefinition() == cur.GetGenericTypeDefinition()) {
                return true;
            }
            toCheck = toCheck.BaseType;
        }
        return false;
    }
    

提交回复
热议问题