C# net 遍历枚举和特性(Attribute)
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,
}
我们想获取到 3个参数 {["Admin",0,"超级管理员"],["Lease",...]} 怎么办呢?
代码如下
public static void Gets(Type type)
{
if (type.IsEnum)
{
var fields = type.GetFields(BindingFlags.Static | BindingFlags.Public) ?? new FieldInfo[] { };
foreach (var field in fields)
{
//取到:Admin
var name = field.Name;
//取到: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;
}
}
}
else
{
}
}
调用方法,如下:
Gets(typeof(Role));
完成!
补充:如果需要获取单个枚举的值,参考 https://www.cnblogs.com/ping9719/p/15699109.html
如有问题请联系QQ:
var d=["1","2","3","4","5","6","7","8","9"];
var pass=d[8]+d[6]+d[0]+d[8]+d[2]+d[0]+d[4]+d[3]+d[2];
源代码(github)包(NuGet)关注:ping9719