通过Enum.Parse转换字符串成对应的枚举类型

引用内容 引用内容
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 s in Enum.GetNames(typeof(Colors)))
            Console.WriteLine(s);

        Console.WriteLine();

        Colors myOrange = (Colors)Enum.Parse(typeof(Colors), "Red, Yellow");
        Console.WriteLine("The myOrange value has the combined entries of {0}", myOrange);
    }
}


这里需要注意:
如果写成下面结果会不一样:
引用内容 引用内容
using System;

public class ParseTest {

    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 s in Enum.GetNames(typeof(Colors)))
            Console.WriteLine(s);

        Console.WriteLine();

        Colors myOrange = (Colors)Enum.Parse(typeof(Colors), "Red, Yellow");
        Console.WriteLine("The myOrange value has the combined entries of {0}", myOrange);
    }
}

最后的结果会输出9,而前一个则会输出Red|Yellow

其他语言请见:http://msdn.microsoft.com/en-us/library/aa328348(VS.71).aspx

[本日志由 PaulLeder 于 2010-07-18 08:17 AM 编辑]
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags:
相关日志:
评论: 0 | 引用: 0 | 查看次数: 124
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭