为什么负面枚举成员最后被foreach枚举?

时间:2013-08-09 14:09:11

标签: c# enums

在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

1 个答案:

答案 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;

可以看出,它是无符号类型,它们包含实际值 - 所以当枚举时发出这些值时,它们自然会处于无符号顺序。