1
Q
如何识别泛型类?
A
回答
4
如果C#这将是这样的:
public class A<T>
{
}
A<int> a = new A<int>();
if (a.GetType().IsGenericType &&
a.GetType().GetGenericTypeDefinition() == typeof(A<>))
{
}
修订:
看起来这是你真正需要的是什么:
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;
0
Public Function IsSubclassOf(ByVal childType As Type, ByVal parentType As Type) As Boolean
Dim isParentGeneric As Boolean = parentType.IsGenericType
Return IsSubclassOf(childType, parentType, isParentGeneric)
End Function
Private Function IsSubclassOf(ByVal childType As Type, ByVal parentType As Type, ByVal isParentGeneric As Boolean) As Boolean
If childType Is Nothing Then
Return False
End If
If isParentGeneric AndAlso childType.IsGenericType Then
childType = childType.GetGenericTypeDefinition()
End If
If childType Is parentType Then
Return True
End If
Return IsSubclassOf(childType.BaseType, parentType, isParentGeneric)
End Function
相关问题
- 1. 如何使用泛型类型的泛型列表泛型类
- 2. 泛型类型和泛型类型定义有什么区别?
- 3. 泛型类的Typedef(别名)
- 4. SharePoint如何识别文件类型?
- 5. 如何识别儿童输入类型
- 6. JdbcTemplate如何识别数据类型?
- 7. PostgreSQL:如何识别数据类型?
- 8. 如何识别URL的认证类型?
- 9. 如何识别numpy的整数类型?
- 10. 如何识别安装程序类型?
- 11. 如何识别帐户类型
- 12. 如何识别SIM卡的类型?
- 13. 如何有一个泛型类型从一个泛型类型
- 14. Swift 3中的泛型类别别名?
- 15. 如何创建泛型类型类
- 16. ExpressJS识别文件类型
- 17. 无法识别的类型
- 18. 识别滚动的类型
- 19. 识别哈希类型
- 20. 未识别Json类型
- 21. 识别噪音类型
- 22. 获取适用于任何类别的泛型类型列表
- 23. 如何绑定泛型类?
- 24. 如何分组泛型类?
- 25. 如何获得泛型类
- 26. 如何创建泛型类
- 27. 如何比较泛型类java的泛型类成员
- 28. 嵌套泛型泛型类
- 29. 泛型类型类
- 30. 泛型类型
?(** new object(of object)**)。GetType()。GetGenericTypeDefinition是gettype(** List **) *** True *** – serhio 2010-03-19 13:47:02
引发非泛型类型的异常:?(新的ArrayList).GetType()GetGenericTypeDefinition是将gettype((名单)) **操作无效由于对象的当前状态** – serhio 2010-03-19 14:23:35
是的,这是正常现象。 – 2010-03-19 14:31:37