简体   繁体   中英

Nested enums with System.Reflection.Emit

I want to create a class with a nested enum.

public class Foo
{
    public enum Views
    {
    }
}

However System.Reflection.Emit.TypeBuilder class has no DefineNestedEnum only DefinedNestedType. ModuleBuilder.DefineEnum exists that let's me create an enum but I find no way to make it nested. Can I create an enum without faking it (ie, using EnumBuilder)?


I moved my solution to an answer below.

See the example at the end of this article , which does exactly what you want. (You use DefineNestedType with the right arguments)

Moving my answer I put in the question to here.


Only thing I can think of is to define a nested type as sealed class that extends System.Enum and define public|static|literal fields with constant values. This is essentially what the C# compiler is doing based on what I've learned by disassembling it. If I do this and reference the assembly Intellisense recognizes it as an enum and functions just like an enum.


This is exactly the method MSDN shows that Jeremy linked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM