拥有自己的属性。
public sealed class ExtrasDisplayAttribute : Attribute
{
public string Name { get; set; }
public string BackgroundColor { get; set; }
}
而这种扩展方法。
namespace ExtensionsNamespace
{
public static class Extensions
{
public static TAttribute GetAttribute<TAttribute>(Enum value) where TAttribute : Attribute
{
return value.GetType()
.GetMember(value.ToString())[0]
.GetCustomAttribute<TAttribute>();
}
}
}
现在您可以像这样从枚举中提取属性。
using static ExtensionsNamespace.Extensions;
//...
var info = GetAttribute<ExtrasDisplayAttribute>(LeadStatus.Created);
var name = info.Name;
var bg = info.BackgroundColor;
//...
public enum LeadStatus : byte
{
[ExtrasDisplay(Name = "Created", BackgroundColor = "Red")] Created = 1,
[ExtrasDisplay(Name = "Assigned")] Assigned = 2,
}
如果您仍想使用原始属性,您也可以拥有它。您应该将这两个属性都应用于单个枚举。
public enum LeadStatus : byte
{
[Display(Name = "Created"), ExtrasDisplay(BackgroundColor = "Red")]Created = 1,
[Display(Name = "Assigned")] Assigned = 2,
}
并提取你想要的每一个。
var name = GetAttribute<DisplayAttribute>(LeadStatus.Created).Name;
var bg = GetAttribute<ExtrasDisplayAttribute>(LeadStatus.Created).BackgroundColor;