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

*/ 

复制代码
posted @ 2014-03-19 13:31  邹邹  Views(5595)  Comments(0)    收藏  举报