將(jiang)不確定變為確定~Flag特性的(de)枚舉(ju)是否可以得(de)到Description信(xin)息
之前我寫過對于普通枚舉類型對象,輸出Description特性信息的方法,今(jin)天主(zhu)要來說一(yi)下,如何實現位域Flags枚舉元素的Description信息的方(fang)法。
對(dui)于一個普通枚舉(ju)對(dui)象(xiang),它輸出描(miao)述信息是(shi)這樣(yang)的
public enum Status { [Description("正(zheng)常")] Normal = -1, [Description("刪除")] Deletet = 0, [Description("凍結")] Freezed = 1, }
Status status = Status.Normal;
Console.WriteLine(status.GetDescription());
而對于支持位域Flags特性的枚舉來說,在使用GetDescription方法(fa)時,是(shi)不(bu)能(neng)實現(xian)的,我們需(xu)要對(dui)它進行一(yi)些改造。
[Flags] public enum Ball { [Description("足(zu)球")] FootBall = 1, [Description("籃球")] BasketBall = 2, [Description("乒(ping)乓球")] PingPang = 4, }
/// <summary> /// 枚舉類型擴展方(fang)法 /// </summary> public static class EnumExtensions { /// <summary> /// 得到Flags特性(xing)的(de)枚舉的(de)集合 /// </summary> /// <param name="value"></param> /// <returns></returns> static List<Enum> GetEnumValuesFromFlagsEnum(Enum value) { List<Enum> values = Enum.GetValues(value.GetType()).Cast<Enum>().ToList(); List<Enum> res = new List<Enum>(); foreach (var itemValue in values) { if ((value.GetHashCode() & itemValue.GetHashCode()) != 0) res.Add(itemValue); } return res; } /// <summary> /// 獲(huo)取枚(mei)舉變(bian)量值的 Description 屬性 /// </summary> /// <param name="obj">枚(mei)舉變量</param> /// <returns>如果包含 Description 屬性,則返回 Description 屬性的值,否則返回枚舉變量值的名稱</returns> public static string GetDescription(this Enum obj) { string description = string.Empty; try { Type _enumType = obj.GetType(); DescriptionAttribute dna = null; FieldInfo fi = null; var fields = _enumType.GetCustomAttributesData(); if (!fields.Where(i => i.Constructor.DeclaringType.Name == "FlagsAttribute").Any()) { fi = _enumType.GetField(Enum.GetName(_enumType, obj)); dna = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute)); if (dna != null && string.IsNullOrEmpty(dna.Description) == false) return dna.Description; return null; } GetEnumValuesFromFlagsEnum(obj).ToList().ForEach(i => { fi = _enumType.GetField(Enum.GetName(_enumType, i)); dna = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute)); if (dna != null && string.IsNullOrEmpty(dna.Description) == false) description += dna.Description + ","; }); return description.EndsWith(",") ? description.Remove(description.LastIndexOf(',')) : description; } catch { throw; } } }
它在賦值后,輸出是這樣的(de)
Ball ball = Ball.BasketBall | Ball.FootBall;
Console.WriteLine(ball.GetDescription());