#region 从类型成员获取指定的Attribute T特性集合 /// <summary> /// 从类型成员获取指定的Attribute T特性集合 /// </summary> /// <typeparam name="T">Attribute特性类型集合</typeparam> /// <param name="memberinfo">实现了ICustomAttributeProvider接口的类实例</param> /// <param name="inherit">是否从继承中查找,默认不查找</param> /// <returns>存在则返回第一个,不存在返回null</returns> public static T GetAttribute<T>(this ICustomAttributeProvider memberinfo, bool inherit = false) where T : Attribute { return memberinfo.GetCustomAttributes(typeof(T), inherit).SingleOrDefault() as T; } /// <summary> /// 从类型成员获取指定的Attribute T特性集合 /// </summary> /// <typeparam name="T[]">Attribute特性类型</typeparam> /// <param name="memberinfo">实现了ICustomAttributeProvider接口的类实例</param> /// <param name="inherit">是否从继承中查找,默认不查找</param> /// <returns>存在则返回所有特性集合,不存在返回null</returns> public static T[] GetAttributes<T>(this ICustomAttributeProvider memberinfo, bool inherit = false) where T : Attribute { return memberinfo.GetCustomAttributes(typeof(T), inherit).Cast<T>().ToArray(); } #endregion #region 获取是否在此成员上定义一个或多个 attributeType 的实例 /// <summary> /// 获取是否在此成员上定义一个或多个 attributeType 的实例 /// </summary> /// <typeparam name="T">要检查的Attribute特性类</typeparam> /// <param name="memberinfo">要检查的类成员</param> /// <param name="inherit">是否从继承中查找,默认不查找</param> /// <returns>是否存在</returns> public static bool AttributeExists<T>(this ICustomAttributeProvider memberinfo, bool inherit = false) where T : Attribute { return memberinfo.IsDefined(typeof(T), inherit); } #endregion #region 得到成员元数据的Description特性描述信息 /// <summary> /// 得到成员元数据的Description特性描述信息 /// </summary> /// <param name="memberinfo">成员元数据对象</param> /// <param name="inherit">是否从继承中查找,默认不查找</param> /// <returns>存在则返回Description的描述信息,否则返回空</returns> public static string GetDescription(this ICustomAttributeProvider memberinfo, bool inherit = false) { DescriptionAttribute desc = memberinfo.GetAttribute<DescriptionAttribute>(inherit); return desc == null ? String.Empty : desc.Description; } #endregion