C# 动态创建枚举
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/857414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically create an enum
提问by Milen
I have an enum of the following structure:
我有以下结构的枚举:
public enum DType
{
LMS = 0,
DNP = -9,
TSP = -2,
ONM = 5,
DLS = 9,
NDS = 1
}
I'm using this enum to get the names and the values. Since there is a requirement to add more types, I need to read the type and the values from an XML file. Is there any way by which I can create this enum dynamically from XMLfile so that I can retain the program structure.
我正在使用这个枚举来获取名称和值。由于需要添加更多类型,我需要从 XML 文件中读取类型和值。有什么方法可以从XML文件动态创建这个枚举,以便我可以保留程序结构。
采纳答案by Mehrdad Afshari
回答by Rajaram L
Use EnumBuilder to create enums dynamically. This would require usage of Reflection.
使用 EnumBuilder 动态创建枚举。这将需要使用反射。
STEP 1 : CREATING ENUM USING ASSEMBLY/ENUM BUILDER
第 1 步:使用汇编/枚举构建器创建枚举
// 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");
STEP 2: USING THE CREATED ENUM
第 2 步:使用创建的枚举
System.Reflection.Assembly ass = System.Reflection.Assembly.LoadFrom("TempAssembly.dll");
System.Type enumTest = ass.GetType("Elevation");
string[] values = enumTest .GetEnumNames();
Hope that helps
希望有帮助