在C#中,如果我们定义一个包含与负值对应的成员的enum
,然后我们迭代enum
的值,那么负值不是第一个,而是最后一个。为什么会这样?在其他语言(C,C ++,Ada等)中,迭代enum
将为您提供定义它的顺序。
MSDN有一个很好的example of this behavior:
using System;
enum SignMagnitude { Negative = -1, Zero = 0, Positive = 1 };
public class Example
{
public static void Main()
{
foreach (var value in Enum.GetValues(typeof(SignMagnitude)))
{
Console.WriteLine("{0,3} 0x{0:X8} {1}",
(int) value, ((SignMagnitude) value));
}
}
}
// The example displays the following output:
// 0 0x00000000 Zero
// 1 0x00000001 Positive
// -1 0xFFFFFFFF Negative
答案 0 :(得分:15)
从the very documentation page you link to,我的重点:
数组的元素按枚举常量的二进制值(即 unsigned 幅度)进行排序。
深入研究CLR代码(2.0 SSCLI)并且远远低于我真正感到满意的程度,看起来最终这是因为内部枚举值存储在看起来像这样的东西中(注意这是C ++) ):
class EnumEEClass : public EEClass
{
friend class EEClass;
private:
DWORD m_countPlusOne; // biased by 1 so zero can be used as uninit flag
union
{
void *m_values;
BYTE *m_byteValues;
USHORT *m_shortValues;
UINT *m_intValues;
UINT64 *m_longValues;
};
LPCUTF8 *m_names;
可以看出,它是无符号类型,它们包含实际值 - 所以当枚举时发出这些值时,它们自然会处于无符号顺序。