枚举类型是定义了一组“符号名称/值”配对。枚举类型是强类型的。每个枚举类型都是从system.Enum派生,又从system.ValueType派生,而system.ValueType又从system.Object派生,所以枚举类型是指类型。
编译枚举类型时,C#编译器会把每个符号转换成类型的一个常量字段。C#编译器将枚举类型视为基元类型。
1.获取枚举列表:
1.获取枚举列表:
/// <summary>
/// 获取枚举列表
/// </summary>
/// <param>枚举的类型</param>
/// <returns>枚举列表</returns>
public static Dictionary<int, string> GetEnumList(Type enumType)
{
var dic = new Dictionary<int, string>();
try
{
var fd = enumType.GetFields();
for (var index = 1; index < fd.Length; ++index)
{
var info = fd[index];
var fieldValue = System.Enum.Parse(enumType, fd[index].Name);
var attrs = info.GetCustomAttributes(typeof(EnumTextAttribute), false);
foreach (EnumTextAttribute attr in attrs)
{
var key = (int)fieldValue;
if (key == -100) continue;
var value = attr.Text;
dic.Add(key, value);
}
}
return dic;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
2.获取枚举名称:
/// <summary>
/// 获取枚举名称
/// </summary>
/// <param>枚举的类型</param>
/// <param>枚举值</param>
/// <returns>如果枚举值存在,返回对应的枚举名称,否则,返回空字符</returns>
public static string GetEnumTextById(Type enumType, int id)
{
var ret = string.Empty;
try
{
var dic = GetEnumList(enumType);
foreach (var item in dic)
{
if (item.Key != id) continue;
ret = item.Value;
break;
}
return ret;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
3.根据枚举值获取对应中文描述:
/// <summary>
/// 根据枚举值获取对应中文描述
/// </summary>
/// <param>枚举值</param>
/// <returns>枚举值中文描述</returns>
public static string GetEnumTextByEnum(object enumValue)
{
var ret = string.Empty;
if ((int)enumValue == -1) return ret;
try
{
var dic = GetEnumList(enumValue.GetType());
foreach (var item in dic)
{
if (item.Key != (int)enumValue) continue;
ret = item.Value;
break;
}
return ret;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
4.获取枚举名称: