我有以下课程:
public class HtSecurePage : UserControl, IDisposable
{
}
public class HtSecureInstancePage<T1> : HtSecurePage
{
}
public partial class NormalPage : HtSecurePage
{
}
public partial class InstancePage : HtSecureInstancePage<ZlsManager>
{
}
要检查是否NormalPage
是subClass
的HtSecurePage
我用的是以下模式。
if (typeof(NormalPage).BaseType == typeof(HtSecurePage))
{
}
如果我对 使用此模式InstancePage
,则它不起作用。
if (typeof(InstancePage).BaseType == typeof(HtSecureInstancePage<>))
{
}
我需要知道,如果一个Type
是直接subClass
的HtSecurePage
或HtSecureInstancePage<>
。(重要的是不要检查HtSecureInstancePage<ZlsManager>
!)Type T1
未知。
下面的函数检查您的类的子类是否提供了相同类型的类。如果类型是泛型,则在泛型类型定义上执行检查操作。
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句