using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace IoTIntegrationPlatform.Common
{
///
/// 枚举对象操作
///
public static class EnumExtension
{
///
/// 获取枚举的描述信息
///
public static string GetDescription(this Enum em)
{
Type type = em.GetType();
FieldInfo fd = type.GetField(em.ToString());
if (fd == null)
{
return string.Empty;
}
object[] attrs = fd.GetCustomAttributes(typeof(DescriptionAttribute), false);
string name = string.Empty;
foreach (DescriptionAttribute attr in attrs)
{
name = attr.Description;
}
return name;
}
///
/// 获取枚举值描述
///
///
///
public static string GetEnumDescription(this Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes != null && attributes.Length > 0)
{
return attributes[0].Description;
}
else
{
return value.ToString();
}
}
/////
///// 获取枚举值描述(无作用)
/////
/////
/////
/////
//public static string GetDescription(this TEnum value) where TEnum : struct
//{
// return value.ToString(); // 默认返回枚举值的名称,这通常是最好的情况。如果枚举值没有自定义描述属性,将返回名称。
//}
///
/// 根据值获取枚举方法
///
///
///
///
public static Enum GetEnumByValue(Type enumType, string value)
{
return Enum.Parse(enumType, value) as Enum;
}
///
/// 获取枚举列表
///
///
///
public static List> GetEnumArray(this Type type)
{
var result = new List>();
if (type.IsEnum)
{
var values = Enum.GetValues(type);
foreach (var item in values)
{
result.Add(new KeyValuePair(((Enum)item).GetDescription(), (int)item));
}
}
return result;
}
public static List> GetEnumArray(this Type type, params Enum[] notinValue)
{
var result = new List>();
if (type.IsEnum)
{
var values = Enum.GetValues(type);
foreach (var item in values)
{
if (notinValue.Contains((Enum)item))
{
continue;
}
result.Add(new KeyValuePair(((Enum)item).GetDescription(), (int)item));
}
}
return result;
}
}
}