1. 程式人生 > >C#實現獲取列舉的描述

C#實現獲取列舉的描述

一個通用獲取列舉的描述的方法

/// <summary>
        /// 獲取列舉的描述
        /// </summary>
        /// <param name="en">列舉</param>
        /// <returns>返回列舉的描述</returns>
        public static string GetDescription(Enum en)
        {
            Type type = en.GetType();   //獲取型別
            MemberInfo[] memberInfos = type.GetMember(en.ToString());   //獲取成員
            if (memberInfos!=null&&memberInfos.Length>0)
            {
                DescriptionAttribute[] attrs = memberInfos[0].GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];   //獲取描述特性

                if (attrs!=null&&attrs.Length>0)
                {
                    return attrs[0].Description;    //返回當前描述
                }
            }
            return en.ToString();
        }

示例:
/// <summary>
    /// 上傳狀態
    /// </summary>
    public enum UploadState
    {
        [Description("上傳失敗")]
        UploadFailed = -1,

        [Description("正在上傳")]
        Uploading = 0,

        [Description("上傳成功")]
        UploadSuccess = 1
    }

呼叫程式碼:
EnumService.GetDescription(UploadState.UploadSuccess)