判断是否枚举中的匹配项


1.首先定义一个枚举:

 enum Colors { None = 0, Red = 1, Green = 2, Blue = 4 };

2.判断所给的值在枚举中是否存在

 string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
  foreach (string colorString in colorStrings)
  {
         Colors colorValue;
         //将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象
         if (Enum.TryParse(colorString, true, out colorValue))、

        {
                 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);
        }

        else

       {
              Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString);

       }
 }

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM