using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Automatic_Mouse_Click
{
internal static class EnumExt
{
///
/// 枚举转换为列表;Id表示当前序号;value表示常量值
/// 支持自定义显示名称.
///
///
/// 默认常量
/// 扩展显示名
///
internal static List> ViewList(this T item, params string[] displayNames) where T : Enum
{
Type type = typeof(T);
int i = 0;
return Enum.GetNames(type).Select(q =>
{
var itm = new ListItem()
{
Id = Convert.ToInt32(Enum.Parse(type, q)),
Name = q,
DisplayName = displayNames.Length > i ? displayNames[i] : q,
Value = (int)Enum.Parse(type, q),
Type = type.FullName,
IsDefault = Enum.GetName(type, item)?.Equals(q) ?? false,
Icon = "icon-info"
};
++i;
return itm;
}).ToList();
}
///
/// 枚举转换为列表;Id表示当前序号;value表示常量值
/// DisplayName来源于Display属性
/// 如果未标识Display属性,则取当前默认名称
///
///
///
///
internal static List> ViewList(this T item) where T : Enum
{
Type type = typeof(T);
return Enum.GetNames(type).Select(q =>
{
string dname = type.GetField(q)?.GetCustomAttribute()?.Name;
dname = !string.IsNullOrEmpty(dname) ? dname : type.GetField(q)?.GetCustomAttribute()?.Description;
var itm = new ListItem()
{
Id = Convert.ToInt32(Enum.Parse(type, q)),
Name = q,
DisplayName = string.IsNullOrEmpty(dname) ? q : dname,
Value = Enum.Parse(type, q),
Type = type.FullName,
IsDefault = Enum.GetName(type, item)?.Equals(q) ?? false,
Icon = "icon-info"
};
return itm;
}).ToList();
}
///
/// 通过列表对象,反向获取选中的枚举值
///
///
///
///
internal static T EnumValue(this ListItem item) where T : Enum
{
return (typeof(T).FullName?.Equals(item.Type) ?? false) ? (T)item.Value : default;
}
///
/// 获取枚举值的显示名称(未标识则取枚举名称)
///
///
///
internal static string GetDisplay(this T item) where T : Enum
{
Type type = typeof(T);
string f = Enum.GetName(type, item);
string d = type.GetField(f)?.GetCustomAttribute()?.Name;
d = !string.IsNullOrEmpty(d) ? d : type.GetField(f)?.GetCustomAttribute()?.Description;
return d ?? f;
}
///
/// 获取枚举值的名称
///
///
///
///
internal static string GetName(this T item) where T : Enum
{
return Enum.GetName(typeof(T), item);
}
///
/// 通过枚举值获取实际数值
///
///
///
///
internal static int ToInt(this T item) where T : Enum
{
return Convert.ToInt32(item);
}
}
}