没什么好说的,都是些基础!
代码如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace DFS { class Program { static void Main(string[] args) { string boy = GetDescription(Pepole.boy); Console.WriteLine(boy); string Girl = GetDescription(Pepole.girl, true); Console.WriteLine(Girl); string NoSex = GetDescription(Pepole.NoSex, true); Console.WriteLine(NoSex); //枚举自带方法: Array PersonAry = Enum.GetValues(typeof(Pepole));//"Array 类是支持数组的语言实现的基类。但是,只有系统和编译器能够从 Array 类显式派生。用户应当使用由语言提供的数组构造。" foreach (var item in PersonAry) { Console.WriteLine("GetValues结果如下:" + item); } string MyGirl = Enum.GetName(typeof(Pepole),Pepole.girl); Console.WriteLine("我的姑娘如下:"+MyGirl); string[] strAry = new string[] { }; strAry = Enum.GetNames(typeof(Pepole)); foreach (var item in strAry) { Console.WriteLine("GetNames结果如下:" + item); } bool bol = Enum.IsDefined(typeof(Pepole), 1);//true Console.WriteLine(bol); bol = Enum.IsDefined(typeof(Pepole), 33);//false Console.WriteLine(bol); bol = Enum.IsDefined(typeof(Pepole), "boy");//true Console.WriteLine(bol); bol = Enum.IsDefined(typeof(Pepole), "男孩");//false Console.WriteLine(bol); Console.ReadKey(); } /// <summary> /// 操作枚举类 /// </summary> /// <param name="value"></param> /// <returns></returns> public static string GetDescription(Enum value) { FieldInfo fi = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes != null && attributes.Length > 0) return attributes[0].Description; else return value.ToString(); } /// <summary> /// 扩展方法,获得枚举的Description /// </summary> /// <param name="value">枚举值</param> /// <param name="nameInstend">当枚举没有定义DescriptionAttribute,是否用枚举名代替,默认使用</param> /// <returns>枚举的Description</returns> public static string GetDescription(Enum value, bool nameInstend = true) { Type type = value.GetType(); string name = Enum.GetName(type, value); if (name == null) { return null; } FieldInfo field = type.GetField(name); DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute; if (attribute == null && nameInstend == true) { return name; } return attribute == null ? null : attribute.Description; } } public enum Pepole { [Description("男孩")] boy = 1, [Description("女孩")] girl = 2, NoSex=3 } }