Check if a class is derived from a generic class

前端 未结 16 1567
太阳男子
太阳男子 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 10:19

    @EnocNRoll - Ananda Gopal 's answer is interesting, but in case an instance is not instantiated beforehand or you want to check with a generic type definition, I'd suggest this method:

    public static bool TypeIs(this Type x, Type d) {
        if(null==d) {
            return false;
        }
    
        for(var c = x; null!=c; c=c.BaseType) {
            var a = c.GetInterfaces();
    
            for(var i = a.Length; i-->=0;) {
                var t = i<0 ? c : a[i];
    
                if(t==d||t.IsGenericType&&t.GetGenericTypeDefinition()==d) {
                    return true;
                }
            }
        }
    
        return false;
    }
    

    and use it like:

    var b = typeof(char[]).TypeIs(typeof(IList<>)); // true
    

    There are four conditional cases when both t(to be tested) and d are generic types and two cases are covered by t==d which are (1)neither t nor d is a generic definition or (2) both of them are generic definitions. The rest cases are one of them is a generic definition, only when d is already a generic definition we have the chance to say a t is a d but not vice versa.

    It should work with arbitrary classes or interfaces you want to test, and returns what as if you test an instance of that type with the is operator.

提交回复
热议问题