关于带有自定义属性的枚举上的foreach

foreach on enum with Custom Attributes

本问题已经有最佳答案,请猛点这里访问。

如何迭代枚举并获取属性值?

1
2
3
4
5
6
7
8
public enum TableName {
    [DescriptionWithValue("offline","create table offline (uid int, date datetime, id int)")]
    Offline,
    [Description("Online","create table online (uid int, date datetime, id int)")]
    online,
    [Description("Amount","create table amount (uid int, date datetime, id int)")]
    amount
}


你是说像这样?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    class Program
    {
        static void Main()
        {
            foreach (var field in typeof(TableName).GetFields(BindingFlags.Static | BindingFlags.Public))
            {
                ProcessField(field);
            }
        }

        static void ProcessField(FieldInfo field)
        {
            ProcessD(field.GetCustomAttribute(typeof(DescriptionAttribute)) as DescriptionAttribute);
            ProcessDWV(field.GetCustomAttribute(typeof(DescriptionWithValueAttribute)) as DescriptionWithValueAttribute);            
        }

        static void ProcessD(DescriptionAttribute attribute)
        {
            if(attribute != null)
            {
                //...
            }
        }

        static void ProcessDWV(DescriptionWithValueAttribute attribute)
        {
            if (attribute != null)
            {
                //...
            }
        }