通过Enum.Parse转换字符串成对应的枚举类型
作者:PaulLeder 日期:2010-07-18
引用内容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);
}
}
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);
}
}
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
评论: 0 | 引用: 0 | 查看次数: 124
发表评论
上一篇
下一篇

文章来自:
Tags:
相关日志:






