文章出處

定義這樣一個枚舉:

    //顏色枚舉
    internal enum Color
    {
        [Description("紅色")]
        Red=0,

        [Description("綠色")]
        Green=1,

        [Description("藍色")]
        Blue=2
    }

 

 獲取枚舉描述信息的擴展方法:

        private static string GetDescription(this Enum value)
        {
            //得到枚舉類型:返回 命名空間+枚舉名
            var type = value.GetType();

            //得到字段:傳入這個枚舉類型和一個value,得到 枚舉名.值 
            var field = type.GetField(Enum.GetName(type, value));

            if (field == null) return "";

            //得到這個枚舉值所擁有的的標簽中,類型為Description的標簽
            var desc = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;

            //返回這個標簽的Description屬性值
            return desc != null ? desc.Description : "";
        }

 

調用:

        private static void Main(string[] args)
        {
            Color c = Color.Red;
            Console.WriteLine(c.GetDescription());
            Console.ReadKey();
        }

 

使用場景:通過這種思路可以獲取到任意類型的特性標簽的值,上面這個擴展方法可以用于獲取描述信息,生成下拉列表、單選、復選等應用場景,而不用在多個地方編寫重復的文字描述。


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()