[英]Check if class is a subclass of specific generic
I have the following classes: 我有以下课程:
public class HtSecurePage : UserControl, IDisposable
{
}
public class HtSecureInstancePage<T1> : HtSecurePage
{
}
public partial class NormalPage : HtSecurePage
{
}
public partial class InstancePage : HtSecureInstancePage<ZlsManager>
{
}
To check if NormalPage
is a subClass
of HtSecurePage
I use the following pattern. 要检查是否
NormalPage
是一个subClass
的HtSecurePage
我用下面的模式。
if (typeof(NormalPage).BaseType == typeof(HtSecurePage))
{
}
If I use this pattern against InstancePage
, it is not working. 如果我对
InstancePage
使用此模式,它将无法正常工作。
if (typeof(InstancePage).BaseType == typeof(HtSecureInstancePage<>))
{
}
I need to know if a Type
is a direct subClass
of HtSecurePage
or HtSecureInstancePage<>
. 我需要知道,如果一
Type
是直接subClass
的HtSecurePage
或HtSecureInstancePage<>
(It's important not to check against HtSecureInstancePage<ZlsManager>
!) The Type T1
is unknown. ( 重要的是不要检查
HtSecureInstancePage<ZlsManager>
!) Type T1
是未知的。
Below function check your class' sub-class the same type supplied class. 下面的函数检查你的类'子类是否提供相同类型的类。 If types is generic, check operation is executed over generic type definition.
如果类型是通用的,则在泛型类型定义上执行检查操作。
bool isInherited = CheckIsDirectlyInherited(typeof(TestAbstract), new[] {typeof(SecondLevelAbstractClass), typeof(FirstLevelAbstract)});
bool CheckIsDirectlyInherited(Type obj, Type[] baseTypes)
{
if (obj.BaseType == null)
return false;
var objGenericDefinition = obj.BaseType;
if (objGenericDefinition.IsGenericType)
{
objGenericDefinition = objGenericDefinition.GetGenericTypeDefinition();
}
foreach (Type baseType in baseTypes)
{
var baseTypeDefinition = baseType;
if (baseTypeDefinition.IsGenericType)
baseTypeDefinition = baseType.GetGenericTypeDefinition();
if (objGenericDefinition == baseTypeDefinition)
return true;
}
return false;
}
is a direct subClass of HtSecurePage
是HtSecurePage的直接子类
I think you already know how to do it 我想你已经知道怎么做了
Console.WriteLine(typeof(HtSecureInstancePage<ZlsManager>).BaseType == typeof(HtSecurePage));
is a direct subClass of HtSecureInstancePage<>
是HtSecureInstancePage <>的直接子类
To check it you can use something like this: 要检查它,你可以使用这样的东西:
static bool IsDirectSubclassOfRawGeneric(Type parent, Type toCheck)
{
return toCheck.BaseType.IsGenericType && parent == toCheck.BaseType.GetGenericTypeDefinition();
}
...
Console.WriteLine(IsDirectSubclassOfRawGeneric(typeof(HtSecureInstancePage<>), typeof(InstancePage)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.