/// <summary> /// Try Get Generic CustomAttribute field by Attribute Name And Field Name return null if there no custom attribute or field /// </summary> /// <typeparam name="T">Generic of the result</typeparam> /// <param name="o">Object to heck custom attribute property</param> /// <param name="attributeName">the attribute checked</param> /// <param name="name">attribute property name</param> /// <param name="getField">switch check field attribute if the object is Enum. </param> /// <returns></returns> /// <returns>switch check field attribute if the object is Enum. </returns> public static T GetObjectAttribute <T>(this Object o, string attributeName, string name, bool getField = true) { var customeAttribute = o.GetObjectCustomAttribute(getField) .Where(b => b.AttributeType.Name == attributeName).FirstOrDefault(); if (customeAttribute == null) { return(default(T)); } var names = customeAttribute.NamedArguments.Where(b => b.MemberName == name).FirstOrDefault(); if (names == null || names.TypedValue == null || names.TypedValue.Value == null) { return(default(T)); } return((T)names.TypedValue.Value); }
/// <summary> /// Try Get List Generic CustomAttribute field by Attribute Name And Field Name return null if there no custom attribute or field /// </summary> /// <typeparam name="T">Generic of the result</typeparam> /// <param name="o">Object to heck custom attribute property</param> /// <param name="attributeName">the attribute checked</param> /// <param name="name">attribute property name</param> /// <param name="getField">switch check field attribute if the object is Enum. </param> /// <returns></returns> public static IEnumerable <T> GetObjectAttributes <T>(this Object o, string attributeName, string name, bool getField = true) { var customeAttribute = o.GetObjectCustomAttribute(getField) .Where(b => b.AttributeType.Name == attributeName).FirstOrDefault(); if (customeAttribute == null) { return(Enumerable.Empty <T>()); } var names = customeAttribute.NamedArguments.Where(b => b.MemberName == name).FirstOrDefault(); if (names == null || names.TypedValue == null || names.TypedValue.Value == null) { return(Enumerable.Empty <T>()); } var types = ((System.Collections.ObjectModel.ReadOnlyCollection <System.Reflection.CustomAttributeTypedArgument>)names.TypedValue.Value) .Select(b => (T)b.Value).ToArray(); return(types); }
/// <summary> /// get DisplayAttribute from input object /// </summary> /// <param name="o">object to get DisplayAttribute</param> /// <param name="getField"></param> /// <returns>switch check field attribute if the object is Enum. </returns> public static DisplayAttribute GetObjectDisplayAttribute(this Object o, bool getField = true) { return(o.GetObjectCustomAttribute <DisplayAttribute>(getField)); }