實作
1.列舉內容
public enum TestEnum
{
[Display(Name = "A", Description = "A")]
A,
[Display(Name = "B", Description = "B")]
B
}
2.建立一個 Enum-Helper
/// <summary>
/// Enum-Helper
/// </summary>
public static class EnumHelper
{
/// <summary>
/// 轉換為 SelectListItem 下拉選單
/// </summary>
/// <returns></returns>
public static IEnumerable<SelectListItem> ToSelectListItem<T>() where T : struct
{
var type = typeof(T);
if (!type.IsEnum)
{
return null;
}
var result = Enum.GetValues(type)
.Cast()
.Select(x => new SelectListItem
{
Value = (x.ToInt()).ToString(),
Text =$"Name:{x.GetName()},Description:{x.GetDescription()}"
});
return result;
}
/// <summary>
/// 取得列舉值
/// </summary>
/// <typeparam name="T">列舉類型</typeparam>
/// <returns></returns>
public static int ToInt(this Enum obj)
{
return Convert.ToInt32(obj);
}
}
3.測試與結果
留言
張貼留言