枚举类型的自定义属性取得

public class EnumUtils
    {
        /// 
        /// get the description
        /// 
        /// 
        /// 
        public static string StringValueOf(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (attributes.Length > 0)
            {
                return attributes[0].Description;
            }

            return value.ToString();
        }

        /// 
        /// get the enum value
        /// 
        /// 
        /// 
        /// 
        public static T EnumValueOf(string value)
        {
            Type enumType = typeof(T);

            string[] names = Enum.GetNames(enumType);

            foreach (string name in names)
            {
                if (stringValueOf((Enum)Enum.Parse(enumType, name)).Equals(value))
                {
                    return (T)Enum.Parse(enumType, name);
                }
            }

            throw new ArgumentException("The string is not a description or value of the specified enum.");
        }
    }

你可能感兴趣的:(.net小应用,attributes,string,class)