public class b1<T>:b1<T,string> { } public class b1<T1, T2>:b1<T1,T2,int> { } public class b1<T1, T2, T3>:c1<T1> { } public class c1<T1> { } public class a1 : b1<string> { } public class a2 : b1<string, int> { } public class a3 : b1<string, int,decimal> { }
如上的类结构关系。
怎么判断a1,a2,a3都继承了b1和c1
可以用 IsAssignableTo
判断
Console.WriteLine(typeof(a1).IsAssignableTo(typeof(b1<string>)));
// True
Console.WriteLine(typeof(a1).IsAssignableTo(typeof(c1<string>)));
// True
Console.WriteLine(typeof(a2).IsAssignableTo(typeof(b1<string>)));
// False
Console.WriteLine(typeof(a2).IsAssignableTo(typeof(c1<string>)));
// True
Console.WriteLine(typeof(a3).IsAssignableTo(typeof(b1<string>)));
// False
Console.WriteLine(typeof(a3).IsAssignableTo(typeof(c1<string>)));
// True
typeof(T).[IsAssignableFrom, IsSubclassOf](typeof(T2))
看看这2个api
感谢各位大佬的回答, 目前找到了一个完美解决方案
https://solutionschecker.com/questions/check-if-a-class-is-derived-from-a-generic-class/
原文是 stackoverflow 上的 Check if a class is derived from a generic class
@dudu: 感谢大佬回复 , 这个是原始的来源