动态创建枚举

我有一个以下结构的枚举:

public enum DType { LMS = 0, DNP = -9, TSP = -2, ONM = 5, DLS = 9, NDS = 1 } 

我正在使用这个枚举来获取名称和值。 由于需要添加更多类型,我需要从XML文件中读取类型和值。 有没有什么办法可以从XML文件中动态创建这个枚举,这样我就可以保留程序结构。

也许你应该考虑使用Dictionary

如果要在编译时动态生成enum ,可能需要考虑T4 。

使用EnumBuilder动态创建枚举。 这需要使用Reflection。

第1步:使用ASSEMBLY / ENUM BUILDER创建枚举

 // Get the current application domain for the current thread. AppDomain currentDomain = AppDomain.CurrentDomain; // Create a dynamic assembly in the current application domain, // and allow it to be executed and saved to disk. AssemblyName aName = new AssemblyName("TempAssembly"); AssemblyBuilder ab = currentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.RunAndSave); // Define a dynamic module in "TempAssembly" assembly. For a single- // module assembly, the module has the same name as the assembly. ModuleBuilder mb = ab.DefineDynamicModule(aName.Name, aName.Name + ".dll"); // Define a public enumeration with the name "Elevation" and an // underlying type of Integer. EnumBuilder eb = mb.DefineEnum("Elevation", TypeAttributes.Public, typeof(int)); // Define two members, "High" and "Low". eb.DefineLiteral("Low", 0); eb.DefineLiteral("High", 1); // Create the type and save the assembly. Type finished = eb.CreateType(); ab.Save(aName.Name + ".dll"); 

第2步:使用创建的枚举

 System.Reflection.Assembly ass = System.Reflection.Assembly.LoadFrom("TempAssembly.dll"); System.Type enumTest = ass.GetType("Elevation"); string[] values = enumTest .GetEnumNames(); 

希望有所帮助