有一列舉型別如下
enum Family : int { [Description("爸爸")] Father = 0, [Description("媽媽")] Mother = 1, [Description("兄弟")] Brother = 2, [Description("姐妹")] Sister = 3, [Description("兒子")] Son = 4, [Description("女兒")] Daughter = 5 }
經由以下函式可取得列舉值的Description屬性值
public string GetDescription(Enum value) { FieldInfo fi = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); return attributes.Length > 0 ? attributes[0].Description : value.ToString(); }
- 經由列舉值取得Description之值
GetDescription(Family.Brother)
-
經由字串值取得Description之值
GetDescription(((Family) Enum.Parse(typeof(Family), "Brother")))
-
經由列舉型別的基底型別數值取得Description之值
GetDescription((Family) Enum.ToObject(typeof(Family), 2))
1.使用時需引入System.ComponentModel及System.Reflection
2.可將此函式改寫為Extension Methods增加使用上的方便性,或參考國外網友使用泛型來達到相同效果
其它參考
http://www.moggoly.me.uk/blog/post/Enum-description-values.aspx
http://blogs.freshlogicstudios.com/Posts/View.aspx?Id=388f7d39-0b90-43bc-b03a-c1f605dfb499
1 comment:
Thank you.
Post a Comment