[.NET] 如何透過 DisplayName 或 Description 自訂 Enum 字串
An enumeration type (or enum type) is a value type defined by a set of named constants of the underlying integral numeric type
enum 由一組整數類型命名的常數定義,其為實值類型。
類型可為 sbyte、byte、short、ushort、int、uint、long、ulong。
public enum Wood : short
{
Mahogany,
Maple,
Cocobolo,
Cedar,
Adirondack,
Alder,
Sitka,
}
常被用來當作”狀態”的判定,如:
if(httpStatus == HttpStatusCode.OK) {
// do something
}
也可能會被哪來當作”下拉選單”的條件,如果單純用enum原本名稱顯示遠遠不夠,故下面示範如何自訂與取得想要的字串
// 擴增函式可以透過 "." 方式使用
Wood.Adirondack.GetDisplayName();
Wood.Adirondack.GetDescription();
用 GetMember
public static string GetDisplayName(this Enum enumValue)
{
var name = enumValue.ToString();
var memberInfos = enumValue.GetType().GetMember(name);
var displayName = name;
if (memberInfos.Any())
{
var attribute = memberInfos.First().GetCustomAttribute<DisplayAttribute>();
displayName = attribute?.GetName() ?? name;
}
return displayName;
}
用 GetField (建議)
public static string GetDescription(this Enum enumValue)
{
var name = enumValue.ToString();
var field = enumValue.GetType().GetField(name);
var description = name;
if (field != null)
{
var attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
description = attribute?.Description ?? name;
}
return description;
}
參考
Enum ToString with user friendly strings
Can my enums have friendly names?
Difference between Display and Description attribute