Enum.Parse(轉)


Enum.Parse()方法。這個方法帶3個參數,第一個參數是要使用的枚舉類型。其語法是關鍵字typeof后跟放在括號中的枚舉類名。第二個參數是要轉換的字符串,第三個參數是一個bool,指定在進行轉換時是否忽略大小寫。最后,注意Enum.Parse()方法實際上返回一個對象引用—— 我們需要把這個字符串顯式轉換為需要的枚舉類型(這是一個取消裝箱操作的例子)。對於上面的代碼,將返回1,作為一個對象,對應於TimeOfDay.Afternoon的枚舉值。在顯式轉換為int時,會再次生成1。

using System; public class ParseTest { [FlagsAttribute] enum Colors { Red = 1, Green = 2, Blue = 4, Yellow = 8 }; public static void Main() { Console.WriteLine("The entries of the Colors Enum are:"); foreach (string colorName in Enum.GetNames(typeof(Colors))) { Console.WriteLine("{0}={1}", colorName, Convert.ToInt32(Enum.Parse(typeof(Colors), colorName))); } Console.WriteLine(); Colors myOrange = (Colors)Enum.Parse(typeof(Colors), "Red, Yellow"); Console.WriteLine("The myOrange value {1} has the combined entries of {0}", myOrange, Convert.ToInt64(myOrange)); Console.ReadLine(); } }

運行結果:

復制代碼
/*
This code example produces the following results:

The entries of the Colors Enum are:
Red=1
Green=2
Blue=4
Yellow=8

The myOrange value 9 has the combined entries of Red, Yellow

*/ 

復制代碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM