In case someone needs a nullable result and it will work in Enums, PropertyInfo and classes, this is how I solved it. This is a modification of the updated solution Darina Dimitrova.
public static object GetAttributeValue<TAttribute, TValue>(this object val, Func<TAttribute, TValue> valueSelector) where TAttribute : Attribute { try { Type t = val.GetType(); TAttribute attr; if (t.IsEnum && t.GetField(val.ToString()).GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() is TAttribute att) { // Applies to Enum values attr = att; } else if (val is PropertyInfo pi && pi.GetCustomAttributes(typeof(TAttribute), true).FirstOrDefault() is TAttribute piAtt) { // Applies to Properties in a Class attr = piAtt; } else { // Applies to classes attr = (TAttribute)t.GetCustomAttributes(typeof(TAttribute), false).FirstOrDefault(); } return valueSelector(attr); } catch { return null; } }
Examples of using:
// Class SettingsEnum.SettingGroup settingGroup = (SettingsEnum.SettingGroup)(this.GetAttributeValue((SettingGroupAttribute attr) => attr.Value) as SettingsEnum.SettingGroup?); // Enum DescriptionAttribute desc = settingGroup.GetAttributeValue((DescriptionAttribute attr) => attr) as DescriptionAttribute; // PropertyInfo foreach (PropertyInfo pi in this.GetType().GetProperties()) { string setting = ((SettingsEnum.SettingName)(pi.GetAttributeValue((SettingNameAttribute attr) => attr.Value) as SettingsEnum.SettingName?)).ToString(); }
Mideus Jun 14 '19 at 19:45 2019-06-14 19:45
source share