/// <summary>
/// 获取枚举名称
/// </summary>
/// <param>枚举的类型</param>
/// <param>枚举值的位置编号</param>
/// <returns>如果枚举值存在,返回对应的枚举名称,否则,返回空字符</returns>
public static string GetEnumTextByIndex(Type enumType, int index)
{
var ret = string.Empty;
var dic = GetEnumList(enumType);
if (index < 0 || index > dic.Count)
return ret;
var i = 0;
foreach (var item in dic)
{
if (i == index)
{
ret = item.Value;
break;
}
i++;
}
return ret;
}
5.获取枚举值:
/// <summary>
/// 获取枚举值
/// </summary>
/// <param>枚举的类型</param>
/// <param>枚举名称</param>
/// <returns>如果枚举名称存在,返回对应的枚举值,否则,返回-1</returns>
public static int GetEnumIdByName(Type enumType, string name)
{
var ret = -1;
if (string.IsNullOrEmpty(name))
return ret;
var dic = GetEnumList(enumType);
foreach (var item in dic)
{
if (string.Compare(item.Value, name, StringComparison.Ordinal) != 0) continue;
ret = item.Key;
break;
}
return ret;
}
6.获取名字对应枚举值:
/// <summary>
/// 获取名字对应枚举值
/// </summary>
/// <typeparam>枚举类型</typeparam>
/// <param>枚举名称</param>
/// <returns></returns>
public static T GetEnumIdByName<T>(string name) where T : new()
{
var type = typeof(T);
var enumItem = (T)TypeDescriptor.GetConverter(type).ConvertFrom("-1");
if (string.IsNullOrEmpty(name))
return enumItem;
try
{
var fd = typeof(T).GetFields();
for (var index = 1; index < fd.Length; ++index)
{
var info = fd[index];
var fieldValue = System.Enum.Parse(type, fd[index].Name);
var attrs = info.GetCustomAttributes(typeof(EnumTextAttribute), false);
if (attrs.Length != 1) continue;
var attr = (EnumTextAttribute)attrs[0];
if (!name.Equals(attr.Text)) continue;
enumItem = (T)fieldValue;
break;
}
return enumItem;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
7.获取枚举值所在的位置编号: