获取枚举描述信息

static class Program

    {

        enum Orientation

        {

            [DescriptionAttribute("东")]

            East,

            [DescriptionAttribute("南")]

            South,

            [DescriptionAttribute("西")]

            West,

            [DescriptionAttribute("北")]

            North

        }

        static string GetDescription<T>(this T value)

        {

            var memInfo = value.GetType().GetMember(value.ToString());

            var attributes = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false).Cast<DescriptionAttribute>();

            if (attributes.Any())

                return attributes.First().Description;

            return string.Empty;

        }

        static void Main()

        {

            foreach (var s in Enum.GetValues(typeof(Orientation)))

            {

                Console.WriteLine("值:{0}\t\t说明:{1}", s.ToString(), s.GetDescription());

            }



            Console.Read();

        }

    }

 

你可能感兴趣的:(枚举)