C#列挙操作拡張クラス

6595 ワード

using System;

using System.Linq;

using System.ComponentModel;



namespace Demo.Common

{

    /// <summary>

    /// Enum 

    /// </summary>

    public static class EnumHelper

    {

        /// <summary>

        ///  (this )

        /// </summary>

        /// <param name="obj"></param>

        /// <returns></returns>

        public static int ToInt(this Enum obj)

        {

            return Convert.ToInt32(obj);

        }



        public static T ToEnum<T>(this string obj) where T : struct

        {

            if (string.IsNullOrEmpty(obj))

            {

                return default(T);

            }

            try

            {

                return (T)Enum.Parse(typeof(T), obj, true);

            }

            catch (Exception)

            {

                return default(T);

            }

        }



        /// <summary>

        ///  

        /// </summary>

        /// <param name="obj"></param>

        /// <returns></returns>

        public static string ToDescriptionString(this Enum obj)

        {

            var attribs = (DescriptionAttribute[])obj.GetType().GetField(obj.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);

            return attribs.Length > 0 ? attribs[0].Description : obj.ToString();

        }



        /// <summary>

        ////// </summary>

        /// <param name="type"></param>

        /// <param name="id"></param>

        /// <returns></returns>

        public static string GetDescriptionString(this Type type, int? id)

        {

            var values = from Enum e in Enum.GetValues(type)

                         select new { id = e.ToInt(), name = e.ToDescriptionString() };



            if (!id.HasValue) id = 0;



            try

            {

                return values.ToList().Find(c => c.id == id).name;

            }

            catch

            {

                return "";

            }

        }

    }

}