C#获得枚举值实例
1.新建枚举类
public enum ActionType { /// <summary> /// 开 /// </summary> [Description("开")] OPEN = 1, /// <summary> /// 关 /// </summary> [Description("关")] CLOSE = 2, /// <summary> /// 移 /// </summary> [Description("移")] MOVE = 2, }
2.定义获取枚举值方法
/// <summary> /// 根据传入的int返回对应枚举属性名称 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="num">进制</param> /// <returns></returns> public static string GetEnumName<T>(int value) { string name = ""; name = Enum.Parse(typeof(T), Enum.GetName(typeof(T), value)).ToString(); return name; } /// <summary> /// 根据传入的枚举属性获得对应值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value"></param> /// <returns></returns> public static int GetEnumValue<T>(string value) { Type type = typeof(T); var schoolId = Enum.Format(type, Enum.Parse(type, value.ToUpper()), "d"); return Convert.ToInt32(schoolId); }
3.调用
static void Main(string[] args) { string Name = GetEnumName<ActionType>(1); // 根据传入的属性值返回对应枚举属性名称 int value = GetEnumValue<ActionType>("Open"); // 根据传入的属性名称获得对应值 int value1 = (int)ActionType.OPEN; // 直接使用枚举类指定属性值 Console.WriteLine($"Name:{Name}"); Console.WriteLine($"value:{value}"); Console.WriteLine($"value:{value1}"); Console.ReadLine(); }
4.结果