一、前言

我们使用枚举类型的时候,很多时候都会在枚举字段中添加一些特性,然后通过反射获取这个特性中的信息。

        public enum PageType
        { 
            [PageType("\xe602")]
            RegMap,

            [PageType("\xe672")]
            PointCloud,

            [PageType("\xe637")]
            ConfigCamera,

            [PageType("\xe62f")]
            ConfigAlg,
        }
        
    [AttributeUsage(AttributeTargets.Field)]
    public class PageTypeAttribute : Attribute
    { 
        public string Icon {  get; set; }
        public PageTypeAttribute(string icon)
        { 
            Icon = icon;
        }
    }

今天总结一下从枚举类型中获取特性的方式。

二、总结

其实,我们可以使用拓展方法,拓展方法返回PageTypeAttribute 类型,然后拓展方法参数使用(this PageType page)不就好了吗?

但是如果后续有新增的枚举类型有需要呢?后续不止PageTypeAttribute 一个特性呢?

所以这里我们需要使用到泛型+父类。
返回对象为T,T必须继承自Attribute;拓展方法参数必须为Enum,它是所有枚举类型的父类。

   public static class EnumExtended
    { 
        /// <summary>
        /// 用于获取枚举类型的特性的泛型方法
        /// </summary>
        /// <typeparam name="T">特性类型对象</typeparam>
        /// <param name="e">枚举类型对象</param>
        /// <returns></returns>
        public static T GetTAttribute<T>(this Enum e) where T:Attribute
        { 
            Type type = e.GetType();
            FieldInfo field = type.GetField(e.ToString());
            if (field.IsDefined(typeof(T), true))
            { 
                T attr = (T)field.GetCustomAttribute(typeof(T));
                return attr;
            }
            return null;
        }
    }

本文地址:https://blog.csdn.net/zhudaokuan/article/details/110285481