C# net 獲取 枚舉 特性 Attribute
C# net 反射獲取 枚舉 Enum 特性 Attribute
net 反射獲取 枚舉 Enum 特性 Attribute
我們有一個這樣子的枚舉
/// <summary>
/// 角色
/// </summary>
public enum Role
{
/// <summary>
/// 超級管理員
/// </summary>
[Description("超級管理員")]
Admin = 0,
/// <summary>
/// 租借用戶
/// </summary>
[Description("租借用戶")]
Lease = 1,
/// <summary>
/// 普通購買用戶
/// </summary>
[Description("普通購買用戶")]
Money = 2,
}
我們想獲取某一個的值和特性,如 {"Lease",1,"租借用戶"}
調用方法:
Get(Role.Lease)
實現代碼:
public static void Get(Enum obj)
{
if (obj == null)
return;
var type = obj.GetType();
//獲取到:Admin
var enumName = Enum.GetName(type, obj);
var field = type.GetField(enumName);
//獲取到:0
var val = (int)field.GetValue(null);
var atts = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (atts != null && atts.Length > 0)
{
//獲取到:超級管理員
var att = ((DescriptionAttribute[])atts)[0];
var des = att.Description;
}
}
完成
補:如需要遍歷枚舉請參考此文章 https://www.cnblogs.com/ping9719/p/15698921.html