日期:2014-05-18  浏览次数:20846 次

枚举问题 请哪位大侠指点
using System;
using System.Collections.Generic;
using System.Text;
namespace 枚举方法
{
   
  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.WriteLine("The myOrange value {1} has the combined entries of {0}",myOrange, Convert.ToInt64(myOrange));这一句的运行的结果为什么是
The myOrange value 9 has the combined entries of red,Yellow?这个9和Red,Yellow是怎么出来的,“Red,Yellow”中“”有什么特殊作用吗?

------解决方案--------------------
Colors myOrange = (Colors)Enum.Parse(typeof(Colors), "Red, Yellow"); 
你所问的问题关键在这句

赋值号前面没什么好说的,定义了这个么变量

后面Enum.Parse方法“将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象”
Enum.Parse的参数,第一个是要转换成为的类型,赋为typeof(Colors),也就是取得Colors的类型作为第一个参数
第二个参数为一个字符串,是要被转换的对象。在这个字符串里你写了RED和YELLOW,就表示要转换这两个值
Enum.Parse方法第二个参数为多个枚举值的时候,是把每个值转换为对应值,然后按二进制位或运算
RED是1,YELLOW是8,也就是0001或上1000,等于1001,也就是9

所以最后一句输出
“The myOrange value {1}” 
{1}代的是Convert.ToInt64(myOrange),把变量myOrange转换为整型,按位或运算是9
“has the combined entries of {0}”
没什么好说的,照样输出