Enum.GetNames()会导致意想不到的才能与负枚举​​常量 [英] Enum.GetNames() results in unexpected order with negative enum constants

查看:116
本文介绍了Enum.GetNames()会导致意想不到的才能与负枚举​​常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下枚举定义(在C#):​​

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

public enum ELogLevel
{
    General = -1,  // Should only be used in drop-down box in Merlinia Administrator log settings
    All = 0,       // Should not be used as a level, only as a threshold, effectively same as Trace
    Trace = 1,
    Debug = 2,
    Info = 3,
    Warn = 4,
    Error = 5,
    Fatal = 6,
    Off = 7        // Should not be used as a level, only as a threshold
}

现在,当我做了一个 Enum.GetNames()这种类型我得到一个字符串数组,如预期9个元素,但秩序是一切,跟踪。 ..,关将军,这不是我所期待的。

Now, when I do an Enum.GetNames() on this type I get a string array with 9 elements as expected, but the order is All, Trace, ... , Off, General, which is not what I was expecting.

下面是枚举的MSDN 文档。 GetNames()

Here's the MSDN documentation for Enum.GetNames():

备注:返回值数组的元素是由排序   枚举常量的值。

"Remarks: The elements of the return value array are sorted by the values of the enumerated constants."

这是怎么回事呢?我可以改变我的计划采取这种功能性考虑,但那种我想知道为什么.NET是做什么它做。

What's going on here? I can change my program to take this "functionality" into account, but I'd kind of like to know why .NET is doing what it's doing.

推荐答案

这是既 GetNames()中的已知错误的GetValues​​() 已报告这里,但最终得到关闭,不会解决:

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

是的,这种方法确实有它返回枚举值排序为无符号类型的数组(-2是0xFFFFFFFE和-1是0xFFFFFFFF在补,这就是为什么他们表现出了在列表的最后一个bug ),而不是返回值进行排序由他们签名的类型。

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.

不幸的是,我们不能改变的GetValues​​的排序顺序,因为我们将打破已写入依赖于当前的排序行为,所有现有的.NET程序[...]

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.

这篇关于Enum.GetNames()会导致意想不到的才能与负枚举​​常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆