C# 遍历enum类型元素、获取最大值、最小值

声明:本文原创,首发于博客园 http://www.cnblogs.com/EasyInvoice/p/6070563.html 转载请注明出处。

--------------------------------

问题一:一个星期有7天,如果想要显示英文可以直接使用 Enum.ToString() 方法获取元素名称,但如果想显示中文该如何做?

问题二:如何遍历枚举类型?

问题三:如何获取枚举类型最大值、最小值?

 

对于问题一,可以为字段增加特性,如 Desc,声明类型时指定该特性的值,如下:

    public enum MyEnum
    { 
        [Desc("星期日")]
        Sunday=100,
        [Desc("星期一")]
        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday
    }

    [Serializable]
    [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
    public class Desc : Attribute
    {
        /// <summary>
        /// 获得字段或属性的中文解释.
        /// </summary>
        /// <value>字段或属性的中文解释.</value>
        public string Value { get; private set; }
        /// <summary>
        /// 初始化创建一个 <see cref="Desc"/> 类的实例, 用于指示字段或属性的解释说明.
        /// </summary>
        /// <param name="value">字段或属性的解释说明.</param>
        public Desc(string value)
        {
            Value = value;
        }
    }

 对于问题二、三,这里介绍两种方法:

1、使用扩展方法

    public static class Util
    {
        /// <summary>
        /// 获得枚举字段的特性(Attribute),该属性不允许多次定义。
        /// </summary>
        /// <typeparam name="T">特性类型。</typeparam>
        /// <param name="value">一个枚举的实例对象。</param>
        /// <returns>枚举字段的扩展属性。如果不存在则返回 <c>null</c> 。</returns>
        public static T GetAttribute<T>(this Enum value) where T : Attribute
        {
            FieldInfo field = value.GetType().GetField(value.ToString());
            return Attribute.GetCustomAttribute(field, typeof(T)) as T;
        }

        /// <summary>
        /// get arrays of enum type
        /// </summary>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static Array Array(this Type enumType)
        {
            return Enum.GetValues(enumType);
        }

        /// <summary>
        /// name of specified enum
        /// </summary>
        /// <param name="enumType"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string Name(this Type enumType, object value)
        {
            Desc desc = ((Enum)value).GetAttribute<Desc>();
            if (desc != null)
                return desc.Value;
            else
                return Enum.GetName(enumType, value);
        }
      
        /// <summary>
        /// maximun of enum type
        /// </summary>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static int Max(this Type enumType)
        {
            Array EnumArray = Enum.GetValues(enumType);
            int max = (int)EnumArray.GetValue(0);
            foreach (int item in EnumArray)
            {
                if (item > max)
                    max = item;
            }
            return max;
        }

        /// <summary>
        /// minimum of enum type
        /// </summary>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static int Min(this Type enumType)
        {
            Array EnumArray = Enum.GetValues(enumType);
            int min = (int)EnumArray.GetValue(0);
            foreach (int item in EnumArray)
            {
                if (item < min)
                    min = item;
            }
            return min;
        }
    }
   

调用代码:

            listBox1.Items.Clear();
            int index = 0;

            Type exEnum = (typeof(MyEnum));
            foreach (MyEnum item in exEnum.Array())
            {
                listBox1.Items.Add(string.Format("元素 [{0}]: {1}", index++, exEnum.Name(item)));
            }
            listBox1.Items.Add(string.Format("最大值: [{0}] ", exEnum.Max()));
            listBox1.Items.Add(string.Format("最小值: [{0}]", exEnum.Min()));

 2、使用类方法 

    public class ExEnum
    {
        public ExEnum(Type _enumType)
        {
            EnumType = _enumType;
        }

        public Type EnumType { get; set; }

        public string Name(object value)
        {
            Desc desc = ((MyEnum)value).GetAttribute<Desc>();
            if (desc != null)
                return desc.Value;
            else 
                return Enum.GetName(EnumType, value);
        }
        public int Max
        {
            get
            {
                int max = (int)Array.GetValue(0);
                foreach (int item in Array)
                {
                    if (item > max)
                        max = item;
                }
                return max;
            }
        }

        public int Min
        {
            get
            {
                int min = (int)Array.GetValue(0);
                foreach (int item in Array)
                {
                    if (item < min)
                        min = item;
                }
                return min;
            }
        }

        public Array Array
        {
            get { return Enum.GetValues(EnumType); }
        }
    }

 调用方法:

            listBox1.Items.Clear();
            int index = 0;
            ExEnum exEnum = new ExEnum(typeof(MyEnum));
            foreach (MyEnum item in exEnum.Array)
            {
                listBox1.Items.Add(string.Format("元素 [{0}]: {1}", index++, exEnum.Name(item)));
            }
            listBox1.Items.Add(string.Format("最大值: [{0}] ", exEnum.Max));
            listBox1.Items.Add(string.Format("最小值: [{0}]", exEnum.Min));        

 运行效果图:

 

posted @ 2021-04-06 10:12  沐汐Vicky  阅读(1104)  评论(0编辑  收藏  举报