C#열거 설명 코드 가져오기

6161 단어 C#
public class MusterEnum
    {
        ///          
        /// </summary>
        /// <param name="e">      </param>
        /// <returns>        </returns>
        public String GetEnumDesc(Enum e)
        {
            FieldInfo EnumInfo = e.GetType().GetField(e.ToString());
            if (EnumInfo == null)
            {
                return "";
            }
            DescriptionAttribute[] EnumAttributes
                = (DescriptionAttribute[])EnumInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (EnumAttributes.Length > 0)
            {
                return EnumAttributes[0].Description;
            }
            return e.ToString();
        }

        /// <summary>
        ///                   
        /// </summary>
        /// <param name="listControl"></param>
        /// <param name="enumType"></param>
        private Dictionary<string, string> BindDesEnumToListControl(System.Type enumType)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach (object enumValue in Enum.GetValues(enumType))
            {
                Enum e = (Enum)enumValue;
                dic.Add(((int)enumValue).ToString(), GetEnumDesc(e));
            }
            return dic;
        }
}

또 하나는 들어오는 열거된 숫자 인덱스에 따라 직접 가져옵니다
        public static string GetEnumDesc<T>(Object obj)
        {
            obj = (T)obj;
            if (obj == null) throw new ArgumentNullException("     null");
            if (!obj.GetType().IsEnum) throw new Exception("       ");
            FieldInfo fieldinfo = obj.GetType().GetField(obj.ToString());

            string str = string.Empty;
            Object[] objs = fieldinfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (objs != null && objs.Length != 0)
            {
                DescriptionAttribute des = (DescriptionAttribute)objs[0];
                str = des.Description;
            }
            return str;
        }

좋은 웹페이지 즐겨찾기