C#中枚举是一个很是好用的类型,用会了以后确实方便了不少。html
项目中一个枚举类型:函数
public enum Version_Type : byte { [Description("1997版")] 版本1997 = 0 , [Description("2007版")] 版本2007 }
枚举类型的默认类型是int型,能够改变其使用的类型,须要用(: <type>)来进行设置,上例中<type>为byte,也能够用其它类型(byte,sbyte,short,ushort,int,uint,long,ulong)ui
访问控制符不能够为private,protected或者protected internalspa
枚举有描述,枚举变量,枚举值。code
枚举描述能够没有,须要声明如上例须要加上引用 using System.ComponentModel;orm
枚举变量不容许特殊字符(-,空格或者括号之类的(具体的之后补充)),容许使用下划线(_)不能以数字开头。由于枚举变量名称这些限制,因此有时候须要用描述来进行处理(如上例中枚举变量必须使用字符开头,全部须要对用户显示版本信息的时候“1997版”就不能直接当枚举变量,只能使用“版本1997”,有人说这样也能接受啊,可是当要有其它说明的时候好比有空格之类的特殊说明性文字就无法转换了。在C#利用反射动态根据传入属性建立对应控件文章中动态传入枚举,而后列出全部枚举项名称,由于枚举名称限制,因此后来改为了列出全部描述,而后选择描述名称,经过描述名称设置枚举值,即后文将介绍的枚举的扩展用法)htm
枚举值本身定义,能够从零开始(默认也是0),下一个变量若是没有指定值则为上一个变量值+1,如上例中“版本2007”的值为1.对象
枚举转换:blog
1 Version_Type myVersion = Version_Type.版本1997; 2 byte version = (byte)myVersion;//获取值 3 myVersion = (Version_Type )version;//获取枚举 4 string versionName = myVersion.ToString();//获取枚举名称 5 versionName = Convert.ToString(myVersion);//获取枚举名称和上一个同样 6 string versionName1 = "版本2007"; 7 Version_Type myVersion1 = (Version_Type )Enum.Parse(typeof(Version_Type),versionName1);//经过枚举名称获取枚举
枚举扩展用法,经过枚举描述设置枚举值:索引
这个方法关键仍是对枚举描述和枚举变量进行记录。
建立一个Dictionary全局对象:
private Dictionary<int,Dictionary<string,string>> enumValue;
int是用来存放属性索引,表示第i个属性。中间的Dictionary用来存放枚举描述和枚举变量名称,一一对应!
Type t = spec.GetType();//获取类型 for(int i=0;i<GetProperties().Getlength(0);i++) { string text = pi.GetValue(spec,null).ToString(); //其它执行代码 .... //若是是枚举类型 if(pi.PropertyType.BaseType.Name == "Enum") { //建立ComboBoxCell ... //建立Dictionary 记录描述和属性的键值对 Dictionary<string,string> itemEnum = new Dictionary<string,string>(); //属性添加到 ComboBoxCell中 foreach(var fi in pi.PropertyType.GetFields(BindingFlags.Static | BindingFlags.Public)) { /********上篇文章用法********** string text = fi.Name; //text添加到控件中 ****************************/ object[] objs = fi.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute),false); if(objs != null) { //获取描述 string strDescription = ((System.ComponentModel.DescriptionAttribute)objs[0]).Description; //添加描述到控件中 ... //集合中添加简直对 itemEnum.Add(strDescription,fi.Name); continue; } //若是没有描述的状况 string strText = fi.Name; //就用属性本身构成键值对 itemEnum.Add(strText,strText); } EnumValue.Add(i,itemEnum);
} }
当DataGridView中某一项改变的时候,在CellValidating事件处理函数中取出索引,取出要改变的值
string strValue = e.FormattedValue.ToString(); int index = e.RowIndex; string strValueSet = ""; //获取描述对应的枚举属性 if(EnumValue.ContainsKey(index)) { strValueSet = EnumValue[index][strValue]; } //后面修改值代码