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

时间:2018-08-31 09:23:18

标签: c#

我有以下课程:

public class HtSecurePage : UserControl, IDisposable
{

}

public class HtSecureInstancePage<T1> : HtSecurePage
{

}

public partial class NormalPage : HtSecurePage
{

}

public partial class InstancePage : HtSecureInstancePage<ZlsManager>
{

}

要检查NormalPage是否为subClass的{​​{1}},我使用以下模式。

HtSecurePage

如果我对if (typeof(NormalPage).BaseType == typeof(HtSecurePage)) { } 使用此模式,则它不起作用。

InstancePage

我需要知道if (typeof(InstancePage).BaseType == typeof(HtSecureInstancePage<>)) { } Type还是subClass的直接HtSecurePage。 (重要是不要对HtSecureInstancePage<>进行检查!)HtSecureInstancePage<ZlsManager>是未知的。

2 个答案:

答案 0 :(得分:2)

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

方法用法

Metadata:
  AWS::CloudFormation::Init:
  ...
  AWS::CloudFormation::Authentication: 
    S3AccessCreds: 
      type: "S3"
      buckets: 
        - "mybucket"
      roleName: 
        Ref: "myRole"

方法

bool isInherited = CheckIsDirectlyInherited(typeof(TestAbstract), new[] {typeof(SecondLevelAbstractClass), typeof(FirstLevelAbstract)});

答案 1 :(得分:1)

  

是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)));