【问题标题】:How to test whether or not a given type is a static class?如何测试给定类型是否是静态类?
【发布时间】:2010-10-08 14:34:45
【问题描述】:
var types=from m in System.Reflection.Assembly.Load("System").GetTypes()
                  where m.IsClass
                  where // something to check whether or not the type is a static class.
                  select m;

我想从我的结果中填写任何静态类。

【问题讨论】:

标签: c#


【解决方案1】:
var types = from m in System.Reflection.Assembly.Load("System").GetTypes()
            where m.IsClass && m.IsAbstract && m.IsSealed
            select m;

来自this thread

编辑:检查 m.IsSealed

【讨论】:

    【解决方案2】:

    无论您做什么都将基于启发式 - 在 IL 级别没有特定的“此类是静态的”。并且无法保证 C# 和 VB 编译器在未来版本中将如何实现静态/模块。

    好吧,静态类将没有公共构造函数,并且会被密封,所以以下可能就足够了:

        var types=from m in System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
                  where m.IsClass && (!m.IsSealed || m.GetConstructors().Any())
                  select m;
    

    【讨论】:

      【解决方案3】:

      您需要检查该类是否为 Sealed 和 Abstract。
      CLR 不知道静态类,但它支持密封抽象类,即使您无法显式编译它们,静态类也被编译为密封抽象类。

      【讨论】:

        猜你喜欢
        • 2010-11-13
        • 1970-01-01
        • 2011-01-27
        • 1970-01-01
        • 1970-01-01
        • 2012-06-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多