为了账号安全,请及时绑定邮箱和手机立即绑定

检查类是否是特定泛型的子类

检查类是否是特定泛型的子类

C#
一只萌萌小番薯 2021-12-25 16:29:02
我有以下课程: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未知。
查看完整描述

2 回答

?
慕码人2483693

TA贡献1860条经验 获得超9个赞

下面的函数检查您的类的子类是否提供了相同类型的类。如果类型是泛型,则在泛型类型定义上执行检查操作。


方法使用

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;

}


查看完整回答
反对 回复 2021-12-25
?
翻过高山走不出你

TA贡献1875条经验 获得超3个赞

是 HtSecurePage 的直接子类


我想你已经知道怎么做了


Console.WriteLine(typeof(HtSecureInstancePage<ZlsManager>).BaseType == typeof(HtSecurePage));

是 HtSecureInstancePage<> 的直接子类


要检查它,您可以使用以下内容:


static bool IsDirectSubclassOfRawGeneric(Type parent, Type toCheck)

{

    return toCheck.BaseType.IsGenericType && parent == toCheck.BaseType.GetGenericTypeDefinition();

}

...

Console.WriteLine(IsDirectSubclassOfRawGeneric(typeof(HtSecureInstancePage<>), typeof(InstancePage)));



查看完整回答
反对 回复 2021-12-25
  • 2 回答
  • 0 关注
  • 188 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号