using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Net; using System.Reflection; namespace BITKit { public static class DisplayAttributeExtensions { public static string GetDisplayName(this PropertyInfo self) { if (self.GetCustomAttribute() is not { } displayNameAttribute) return self.Name; var name = displayNameAttribute.DisplayName; return string.IsNullOrEmpty(name) ? self.Name : name; } public static string GetDisplayName(this FieldInfo self) { if (self.GetCustomAttribute() is not { } displayNameAttribute) return self.Name; var name = displayNameAttribute.DisplayName; return string.IsNullOrEmpty(name) ? self.Name : name; } public static string GetDisplayName(this object self) { { var type = self is Type t? t: self.GetType(); if (type.GetCustomAttribute() is { } displayNameAttribute) { return displayNameAttribute.DisplayName; } #if NET5_0_OR_GREATER if (type.GetCustomAttribute() is { } displayAttribute) { return displayAttribute.Name; } #endif } { if (self is not Enum) return self.ToString(); var field = self.GetType().GetField(self.ToString()!); if(field is null) return self.ToString(); if (field.GetCustomAttribute() is { } displayNameAttribute) { return displayNameAttribute.DisplayName; } #if NET5_0_OR_GREATER if (field.GetCustomAttribute() is { } displayAttribute) { return displayAttribute.Name; } #endif } return self.ToString(); } } }