Enum.GetNames() results in unexpected order with negative enum constants

后端 未结 2 1357
深忆病人
深忆病人 2021-01-08 01:20

I have the following enum definition (in C#):

public enum ELogLevel
{
    General = -1,  // Should only be used in drop-down box in Merlinia Administrator lo         


        
相关标签:
2条回答
  • 2021-01-08 01:21

    This is a known bug with both GetNames() and GetValues() that was reported here, but ended up getting closed as won't fix:

    Yes, this method indeed has a bug where it returns the array of enum values sorted as unsigned-types (-2 is 0xFFFFFFFE and -1 is 0xFFFFFFFF in two's complement, that's why they are showing up at the end of the list) instead of returning values sorted by their signed-types.

    Unfortunately, we cannot change the sort order of GetValues because we will break all existing .NET programs that have been written to depend on the current sorting behavior [...]

    Looks like you'll have to reorder the values yourself.

    0 讨论(0)
  • 2021-01-08 01:35

    Depending on how the sorting occurs, it may be that it is sorting the values as if they were unsigned, in which case, -1 = 0xffffffff, which is of course greater than 7.

    0 讨论(0)
提交回复
热议问题