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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:25:58  来源:igfitidea点击:

Dynamically create an enum

c#

提问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

Probably, you should consider using a Dictionary<string, int>instead.

也许,您应该考虑使用 aDictionary<string, int>代替。

If you want to generate the enumat compile-timedynamically, you might want to consider T4.

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

回答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

希望有帮助