我怎样才能识别(.NET2)一个泛型类?
Class A(Of T)
End Class
' not work '
If TypeOf myObject Is A Then
?
如果用 c# 的话会是这样的:
public class A<T>
{
}
A<int> a = new A<int>();
if (a.GetType().IsGenericType &&
a.GetType().GetGenericTypeDefinition() == typeof(A<>))
{
}
UPDATED:
看起来这就是您真正需要的:
public static bool IsSubclassOf(Type childType, Type parentType)
{
bool isParentGeneric = parentType.IsGenericType;
return IsSubclassOf(childType, parentType, isParentGeneric);
}
private static bool IsSubclassOf(Type childType, Type parentType, bool isParentGeneric)
{
if (childType == null)
{
return false;
}
childType = isParentGeneric && childType.IsGenericType ? childType.GetGenericTypeDefinition() : childType;
if (childType == parentType)
{
return true;
}
return IsSubclassOf(childType.BaseType, parentType, isParentGeneric);
}
并且可以像这样使用:
public class A<T>
{
}
public class B : A<int>
{
}
B b = new B();
bool isSubclass = IsSubclassOf(b.GetType(), typeof (A<>)); // returns true;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)