MSIL实用指南-创建枚举类型
创建枚举类型比较简单,主要使用moduleBuilder.DefineEnum 和enumBuilder.DefineLiteral。
第一步:创建 EnumBuilder
创建 EnumBuilder用moduleBuilder.DefineEnum方法,参数是(<枚举类型名称>,<访问控制符>,<类型>)
具体例子是这样
EnumBuilder enumBuilder = moduleBuilder.DefineEnum(namespaceName + "." + typeName, TypeAttributes.Public, typeof(int));
用TypeAttributes.Private或者typeof(long)都是可以的。
第一步:创建枚举项
创建枚举项用enumBuilder.DefineLiteral(<枚举项名称>, <枚举值>);
例如
FieldBuilder builderRed = enumBuilder.DefineLiteral("Red", 1);
完整程序如下
using System; using System.Reflection; using System.Reflection.Emit; namespace LX1_ILDemo { class Demo06_Enum { static string binaryName = "Demo06_Enum.dll"; static string namespaceName = "LX1_ILDemo"; static string typeName = "EnumCreate"; static AssemblyBuilder assemblyBuilder; static ModuleBuilder moduleBuilder; static EnumBuilder enumBuilder; static void Create_Enum() { enumBuilder = moduleBuilder.DefineEnum(namespaceName + "." + typeName, TypeAttributes.Public, typeof(int)); FieldBuilder builderRed = enumBuilder.DefineLiteral("Red", 1); FieldBuilder builderYellow = enumBuilder.DefineLiteral("Yellow", 2); FieldBuilder builderBlue = enumBuilder.DefineLiteral("Blue", 3); } public static void Generate() { InitAssembly(); Create_Enum(); SaveAssembly(); Console.WriteLine("生成成功"); } static void InitAssembly() { AssemblyName assemblyName = new AssemblyName(namespaceName); assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave); moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, binaryName); } static void SaveAssembly() { Type t = enumBuilder.CreateType(); assemblyBuilder.Save(binaryName); } } }
View Code