Enumeration daily development pricey frequency or, where the record about a simple conversion
methods required by
the above methods, may be enumerated value or values, into a corresponding enumeration object
simple-packaged
/// <summary>
/// ID获取对应枚举
/// </summary>
/// <typeparam name="T">枚举类型</typeparam>
/// <param name="id"></param>
/// <exception cref="Exception"></exception>
/// <returns></returns>
public static T GetEnumByIDorName<T>(dynamic value) where T : struct, Enum
{
if (Enum.TryParse(value.ToString(), out T type))
{
return type;
}
throw new Exception("获取枚举格式失败");
}
Instructions
/// <summary>
/// 城市
/// </summary>
public enum City
{
HangZhou = 1,
BeiJing = 0,
ShangHai = 2,
ShenZhen = 3
}
//获取ShangHai对应枚举对象
City city_1 = GetEnumByIDorName<City>("ShangHai");
//获取数值3对象的枚举对象
City city_2 = GetEnumByIDorName<City>(3);
Enumerated objects, get the object character and numeric values
string name = city_1.ToString(); //name="ShangHai"
int cnt = (int)city_2; //cnt=3;