使用ModuleBuilder将一个类标记为`internal static`

3

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

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

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

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


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

4

使用以下方法使其起作用:

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

这提供了我想要的 internal static

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接