【问题标题】:Marking a class as `internal static` using ModuleBuilder使用 ModuleBuilder 将类标记为“内部静态”
【发布时间】:2014-07-26 05:15:04
【问题描述】:

我正在使用 Reflection.Emit 生成一个动态程序集,一切正常,但是由于以下代码,生成的类被标记为 internal sealed

var typeBuilder = moduleBuilder.DefineType("MyNamespace.Program", TypeAttributes.Class | TypeAttributes.Sealed);

我没有看到任何TypeAttributes 成员会暗示static。它似乎不仅仅是一种编译器的便利,因为我可以看到手动编写的类在反射器工具中显示为 static

如何将自己的类型标记为静态?

【问题讨论】:

  • 静态类是一个 C# 概念,在 IL 级别不存在。在 IL 中,您需要通过静态类的两个定义属性来表示它:它不能被实例化(即它是抽象的)并且它不能派生自它(即它是密封的)。
  • @CodesInChaos:谢谢。我知道这一点,但在查看类型构建器时并没有考虑到这一点。很可能是因为我习惯了在仅查询反射中使用的 BindingFlags。

标签: c# .net class reflection static


【解决方案1】:

使用:

var builderType = builderModule.DefineType("MyNamespace.Program", TypeAttributes.Class | TypeAttributes.NotPublic | TypeAttributes.Sealed | TypeAttributes.Abstract);

这给了我想要的internal static

【讨论】:

    猜你喜欢
    • 2012-02-03
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    相关资源
    最近更新 更多