我我的感受平日用到的enum应该是很是简单的,无非就是枚举和整数、字符串之间的转换。最近工做发现一些同事竟然不太会用这个东东,因而就整理一下。缓存
枚举类型是定义了一组“符号名称/值”配对。枚举类型是强类型的。每一个枚举类型都是从system.Enum派生,又从system.ValueType派生,而system.ValueType又从system.Object派生,因此枚举类型是值类型。编译枚举类型时,C#编译器会把每一个符号转换成类型的一个常量字段。C#编译器将枚举类型视为基元类型。由于enum是值类型,而全部的值类型都是sealed,因此在扩展方法时都不能进行约束。可是,若要限制参数为值类型,可用struct 约束。由于enum通常用于一个字符串和整数值,若是咱们须要关联多个字符串的时候可使用Description特性,若是枚举彼此须要与或运算,须要借助Flags特性,enum里面定义的字符常量其整数值默认从0开始。性能
看一下枚举定义:this
public enum AwardType { /// <summary> ///1 积分 /// </summary> [Description("积分")] Integral = 1, /// <summary> /// 2 充值卡 /// </summary> [Description("充值卡")] RechargeCard = 2, /// <summary> /// 3 实物奖品 /// </summary> [Description("实物奖品")] Gift = 3, } public static class Extend { public static string Description<T>(this T instance) where T : struct { string str = string.Empty; Type type = typeof(T); if (!typeof(T).IsEnum) { throw new ArgumentException("参数必须是枚举类型"); } var fieldInfo = type.GetField(instance.ToString()); if (fieldInfo != null) { var attr = fieldInfo.GetCustomAttribute(typeof(DescriptionAttribute), false) as DescriptionAttribute; if (attr != null) { str = attr.Description; } else { str = fieldInfo.Name; } } return str; } public static T GetEnum<T>(this string description) { var fieldInfos = typeof(T).GetFields(); foreach (FieldInfo field in fieldInfos) { DescriptionAttribute attr = field.GetCustomAttribute(typeof(DescriptionAttribute), false) as DescriptionAttribute; if (attr != null && attr.Description == description) { return (T)field.GetValue(null); } else if (field.Name == description) { return (T)field.GetValue(null); } } throw new ArgumentException(string.Format("{0} 未能找到对应的枚举.", description), "Description"); } }
编译后以下:编码
在编码的时候 必要的注释 不能缺乏,以下spa
/// <summary>
/// 3 实物奖品
/// </summary>3d
这样VS在只能感知的时候就能够看到了。code
而枚举的应用也很是简单:orm
static void Main(string[] args) { //枚举与整数转换 int giftInt = (int)AwardType.Gift; var a = (AwardType)giftInt; //枚举与字符串转换 string giftStr = AwardType.Gift.ToString(); Enum.TryParse(giftStr, out AwardType b); ///检测枚举是否有效 bool isdefine = Enum.IsDefined(typeof(AwardType), 1); ////获取枚举描述 string str = AwardType.Gift.Description(); ////经过描述获取枚举 AwardType award = str.GetEnum<AwardType>(); Console.ReadKey(); }
这里枚举和其描述信息是直接经过反射来实现的,为了性能提升能够采用字典缓存数据。blog