代码之家  ›  专栏  ›  技术社区  ›  Binary Worrier

如何判断类型是否是静态类?[副本]

  •  10
  • Binary Worrier  · 技术社区  · 15 年前

    可能重复:
    Determine if a type is static

    确定类型是否为静态

    是否有我可以检查的属性 System.Type 是静态类吗?

    我可以通过测试 Type System.Object 但是它没有 干净(我有一个隐秘的怀疑,我遗漏了一些东西,这个定义不够严格 static class ).

    有没有什么我遗漏的东西会断然告诉我 这是一个静态类

    或是 静态类 c#语法糖,没有办法用IL来表达?

    谢谢

    3 回复  |  直到 8 年前
        1
  •  14
  •   jasper johnz    15 年前

    是的,你需要同时测试 IsAbstract IsSealed

        2
  •  8
  •   Stefan P.    15 年前

    在IL级别,任何静态类都是抽象和密封的。所以你可以这样做:

        Type myType = typeof(Form1);
        if (myType.GetConstructor(Type.EmptyTypes) == null && myType.IsAbstract && myType.IsSealed)
        {
            // class is static
        }
    
        3
  •  3
  •   Saeed Amiri    15 年前
            if (typeof(C).Attributes.HasFlag(System.Reflection.TypeAttributes.Abstract) &&
                 typeof(C).Attributes.HasFlag(System.Reflection.TypeAttributes.Sealed) && 
                typeof(C).Attributes.HasFlag(System.Reflection.TypeAttributes.Class) )
                {
                }
    

    但是可能有一个具有这个属性的类,但它不是静态的