Search for a string in Enum and return the Enum

后端 未结 12 2227
礼貌的吻别
礼貌的吻别 2020-11-28 19:13

I have an enumeration:

public enum MyColours
{
    Red,
    Green,
    Blue,
    Yellow,
    Fuchsia,
    Aqua,
    Orange
}

and I have a s

12条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 20:02

    class EnumStringToInt // to search for a string in enum
    {
        enum Numbers{one,two,hree};
        static void Main()
        {
            Numbers num = Numbers.one; // converting enum to string
            string str = num.ToString();
            //Console.WriteLine(str);
            string str1 = "four";
            string[] getnames = (string[])Enum.GetNames(typeof(Numbers));
            int[] getnum = (int[])Enum.GetValues(typeof(Numbers));
            try
            {
                for (int i = 0; i <= getnum.Length; i++)
                {
                    if (str1.Equals(getnames[i]))
                    {
                        Numbers num1 = (Numbers)Enum.Parse(typeof(Numbers), str1);
                        Console.WriteLine("string found:{0}", num1);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Value not found!", ex);
            }
        }
    }
    

提交回复
热议问题