Description and value of c# enumeration

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication15
{
    class Program
    {

    
        public static string FetchDescription(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes =
               (DescriptionAttribute[])fi.GetCustomAttributes(
               typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
        }

        static void Main(string[] args)
        {
            TestEnum testEnum = TestEnum.one;
          
            // Get the description           
            string of the enumeration thisValue = FetchDescription(testEnum);
             // Get the value of the enumeration 
            var val = ( int )testEnum;

        }

    }


    public  enum TestEnum
    {
        [Description( " Hello everyone, this is the description " )]
        one = 1,
        two = 2,
        three = 3
    }
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325301237&siteId=291194637