判斷是否枚舉中的匹配項


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