我创建的枚举如下所示:
enum MonthOfTheYear : byte
{
January,
February,
March,
April,
May,
June,
July = 0,
August,
September,
October,
November,
December
}
如您所见,July 的初始值设定项为 0。这有一些有趣的(副作用):似乎存在整数值的“配对”。二月和八月现在的值为 1,三月和九月的值为 2,依此类推:
MonthOfTheYear theMonth = MonthOfTheYear.February;
Console.WriteLine(theMonth + " has integer value of " + (int)theMonth);
和
MonthOfTheYear theMonth = MonthOfTheYear.August;
Console.WriteLine(theMonth + " has integer value of " + (int)theMonth);
清楚地表明这一点。到目前为止,我觉得很奇怪,我愿意一起去。 编辑:我知道分配 7 月 0 日会使索引重新开始。我不明白为什么它们可以在同一个枚举中共存。
但!如果我然后循环遍历枚举并输出所有底层整数值,就会发生奇怪的事情。
MonthOfTheYear theMonth = MonthOfTheYear.January;
for (int i = 0; i < 12; i++)
{
Console.WriteLine(theMonth + " has integer value of " + (int)theMonth++);
}
输出
July has integer value of 0
February has integer value of 1
September has integer value of 2
April has integer value of 3
May has integer value of 4
June has integer value of 5
6 has integer value of 6
7 has integer value of 7
8 has integer value of 8
9 has integer value of 9
10 has integer value of 10
11 has integer value of 11
我希望有人可以向我解释幕后发生的事情,因为整数值是连续的,所以我认为这是按预期输出的,但我还没有看到它。