在專案底下新增資料夾 Extension,建立類別
/// <summary>擴充功能</summary>
public static class CHelpExtensions
{
/// <summary>
/// 取得列舉定義的字串
/// </summary>
/// <param name="value">列舉</param>
public static string GetDescription(this Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = fi.GetCustomAttributes(
typeof(DescriptionAttribute), false) as DescriptionAttribute[];
//若取不到屬性,則取名稱
return attributes.Length > 0 ?
attributes[0].Description : value.ToString();
}
}
定義Enum
/// <summary>範例</summary>
public class ExampleEnum
{
/// <summary>狀態</summary>
public enum EStatus
{
[Description("成功")]
SUCCESS,
[Description("失敗")]
FAILED,
[Description("資料錯誤")]
DATA_ERROR,
[Description("伺服器逾時")]
TIME_OUT,
[Description("伺服器維護中")]
IS_MAINTENANCE,
}
}
使用方式
string statusName = ExampleEnum.EStatus.SUCCESS.GetDescription()