IsK*_*nel 4 c# generics reflection
在以下场景中:
public class A<T> { }
public class B : A<AClass> { }
Run Code Online (Sandbox Code Playgroud)
是否可以在不指定 AClass(泛型参数)的情况下确定 B 是否是 A 的子类?如:
typeof(B).IsSubclassOf(A<>)
Run Code Online (Sandbox Code Playgroud)
是的,但您必须自己通过层次结构:
var instance = new B();
Type t = instance.GetType();
bool isA = false;
while(t != typeof(object))
{
if(t.IsGenericType && t.GetGenericTypeDefinition() == typeof(A<>))
{
isA = true;
break;
}
else
{
t = t.BaseType;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2042 次 |
| 最近记录: |