Why does Enum.Parse create undefined entries?

后端 未结 4 1181
孤独总比滥情好
孤独总比滥情好 2020-12-20 17:09
class Program
{
    static void Main(string[] args)
    {
        string value = "12345";
        Type enumType = typeof(Fruits);
        Fruits fruit = Fr         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-20 17:43

    You need to use Enum.IsDefined:

    http://msdn.microsoft.com/en-us/library/essfb559.aspx

    using System;
    
        [Flags] enum Colors { None=0, Red = 1, Green = 2, Blue = 4 };
    
        public class Example
        {
           public static void Main()
           {
              string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
              foreach (string colorString in colorStrings)
              {
                 try {
                    Colors colorValue = (Colors) Enum.Parse(typeof(Colors), colorString);        
                    if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))  
                       Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
                    else
                       Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString);
                 }
                 catch (ArgumentException) {
                    Console.WriteLine("'{0}' is not a member of the Colors enumeration.", colorString);
                 }
              }
           }
        }
        // The example displays the following output:
        //       Converted '0' to None.
        //       Converted '2' to Green.
        //       8 is not an underlying value of the Colors enumeration.
        //       'blue' is not a member of the Colors enumeration.
        //       Converted 'Blue' to Blue.
        //       'Yellow' is not a member of the Colors enumeration.
        //       Converted 'Red, Green' to Red, Green.
    

提交回复
热议问题