现摘抄MSDN示例如下,请注意中文注释处的疑问
注释1:这里算赋值?或作其它的理解,但为什么有按位或运算符“|”。如果是赋值,那Seasons.Winter 为什么不为4,而是winter?
注释2:这里的表达式和上面差不多,是不是说一个键可以对应多个键值?
注释3:既然e.Value 和 seasons[i] 的值都是字符串值,又怎么可以按位与运算?另外这个if块说明了什么,也就是说 ((Seasons)e.Value & seasons[i]) > 0 能说明什么问题
恭迎各位解答,老夫多谢啦!!!
using System;
using System.Collections;
// A traditional enumeration of some root vegetables.
public enum SomeRootVegetables
{
HorseRadish,
Radish,
Turnip
}
// A bit field or flag enumeration of harvesting seasons.
[Flags]
public enum Seasons
{
None = 0,
Summer = 1,
Autumn = 2,
Winter = 4,
Spring = 8,
All = Summer | Autumn | Winter | Spring // 注释1
}
// Entry point.
public class EnumerationSample
{
public static void Main()
{
// Hash table of when vegetables are available.
Hashtable AvailableIn = new Hashtable();
AvailableIn[SomeRootVegetables.HorseRadish] = Seasons.All;
AvailableIn[SomeRootVegetables.Radish] = Seasons.Spring;
AvailableIn[SomeRootVegetables.Turnip] = Seasons.Spring |
Seasons.Autumn; // 注释2
// Array of the seasons, using the enumeration.
Seasons[] seasons = new Seasons[] { Seasons.Winter, Seasons.Spring,
Seasons.Summer, Seasons.Autumn };
// Print information of what vegetables are available each season.
for (int i = 0; i < seasons.Length; i++)
{
Console.WriteLine("\r\nThe following root vegetables are
harvested in " + seasons[i].ToString("G") + ":");
foreach (DictionaryEntry e in AvailableIn)
{
// A bitwise comparison.
if (((Seasons)e.Value & seasons[i]) > 0) //注释3
Console.WriteLine("\t" +
((SomeRootVegetables)e.Key).ToString("G"));
}
}
}
}
此程序的输出如下所示。
The following root vegetables are harvested in Summer:
HorseRadish
The following root vegetables are harvested in Autumn:
Turnip
HorseRadish
The following root vegetables are harvested in Winter:
HorseRadish
The following root vegetables are harvested in Spring:
Turnip
Radish
HorseRadish
|