使用自定义属性在枚举上进行操作

时间:2018-02-18 12:31:04

标签: c# linq enums

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

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 个答案:

答案 0 :(得分:0)

你的意思是这样吗?

    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)
            {
                //...
            }
        }