如何使用EnumBuilder动态创建枚举时设置属性

时间:2014-10-09 13:09:30

标签: c# xml enums

我必须从XML动态创建Enum。 XML格式如下:

<?xml version="1.0" encoding="utf-8"?>
<Category xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Game>
    <Name>Tekken</Name>
    <Code>10</Code>
  </Game>
  <Game>
    <Name>NFS</Name>
    <Code>20</Code>
  </Game>
  <Game>
    <Name>FinalFa</Name>
    <Code>40</Code>
  </Game>
</Category>

我想创建看起来像这样的Enum:

[DataContract]
[Flags]
public enum Category
{
    [EnumMember]
    Tekken = 10,
    [EnumMember]
    NFS = 20,
    [EnumMember]
    FinalFa = 40,
}

到目前为止,我已经能够创建这个:

 public enum Category
    {
        Tekken = 10,
        NFS = 20,
        FinalFa = 40,
    }

用于生成枚举的C#代码:

   private static void Create()
        {
            AppDomain currentDomain = AppDomain.CurrentDomain;
            AssemblyName asmName = new AssemblyName("EnumAssembly");
            AssemblyBuilder asmBuilder = currentDomain.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave);
            ModuleBuilder mb = asmBuilder.DefineDynamicModule(asmName.Name, asmName.Name + ".dll");
            EnumBuilder eb = mb.DefineEnum("MyNamespace.Category", TypeAttributes.Public, typeof(int));

            FieldBuilder fb1 = eb.DefineLiteral("Tekken", 10);
            FieldBuilder fb2 = eb.DefineLiteral("NFS", 20);
            FieldBuilder fb3 = eb.DefineLiteral("FinalFa", 40);

            Type eType = eb.CreateType();
            asmBuilder.Save(asmName.Name + ".dll");

            foreach (object obj in Enum.GetValues(eType))
            {
                Console.WriteLine("{0}.{1} = {2}", eType, obj, ((int)obj));
            }
        }

如何将[DataContract],[Flags]和[EnumMember]属性添加到我的枚举中?

2 个答案:

答案 0 :(得分:0)

如您所见,DefineLiteral方法返回FieldBuilder(fb1,fb2,fb3)。您可以在FieldBuilder上使用SetCustomAttribute来设置属性。链接的MSDN文章有一个如何使用它的示例。然而,它的要点是使用CustomAttributeBuilder来构建属性,然后将其提供给SetCustomAttribute。

答案 1 :(得分:0)

不完全确定但是这样的事情:

Type myType = typeof(DataContract);
ConstructorInfo myInfo = myType.GetConstructor();

eb.SetCustomAttribute(myInfo);