12

In C#, if we define an enum that contains a member correspondingto a negative value, and then we iterate over that enum's values, the negative value does not come first, but last. Why does that happen? In other languages (C, C++, Ada, etc), iterating over an enum will give you the order in which you defined it.

MSDN has a good 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
4

1 回答 1

16

您链接到的文档页面,我的重点是:

数组的元素按枚举常量的二进制值排序(即按它们的无符号大小)。

深入研究 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;

可以看出,保存实际值的是无符号类型 - 因此,当这些值被发出以进行枚举时,它们自然是按无符号顺序排列的。

于 2013-08-09T14:12:01.413 回答