Enum.GetValues()不会返回你(我)期望的内容

时间:2016-02-18 08:43:04

标签: c# enums

我定义了以下枚举器:

[Flags]
public enum CoinSizes
{
    [Display(Name = "0.01")]
    OneCent = 0x1,
    [Display(Name = "0.02")]
    TwoCent = 0x2,
    [Display(Name = "0.05")]
    FiveCent = 0x4,
    [Display(Name = "0.10")]
    TenCent = 0x8,
    [Display(Name = "0.20")]
    TwentyCent = 0x16,
    [Display(Name = "0.25")]
    TwentyFiveCent = 0x32,
    [Display(Name = "0.50")]
    FiftyCent = 0x64,
    [Display(Name = "1.00")]
    OneDollar = 0x128,
    [Display(Name = "2.00")]
    TowDollar = 0x256,
    [Display(Name = "5.00")]
    FiveDollar = 0x512,
    [Display(Name = "10.00")]
    TenDollar = 0x1024,
    [Display(Name = "25.00")]
    TwentyFiveDollar = 0x2048,
    [Display(Name = "50.00")]
    FiftyDollar = 0x4096
}

我正在构建一个MVC Web应用程序,并且我定义了一个自定义的EnumCheckboxListFor助手。在帮助程序中,我使用Linq迭代Enum项目并检查选择了哪些项目,因此需要检查哪些复选框。

我使用以下内容获取可用枚举的完整列表,然后重复这些列表:

Enum.GetValues((typeof(TEnum)))

LINQ:

TEnum enumValues = expression.Compile()((TModel)htmlHelper.ViewContext.ViewData.Model);
    IEnumerable<SelectListItem> items = Enum
        .GetValues(enumType)
        .Cast<Enum>()
        .Select(c => new SelectListItem
        {
            Text = c.EnumDisplayName().ToString(),
            Value = c.ToString(),
            Selected = enumValues != null && (value.Equals(c) || value.ToString().Contains(c.ToString()))
        }).ToList();

我知道确定&#34;选择&#34;的逻辑。并不完美,但这是一个WIP。主要是,Enum.GetValues()返回的数组是奇数:

Enum.GetValues((typeof(TEnum)))
    {Href.DataStore.Gambling.Core.CoinSizes[13]}
        [0]: OneCent
        [1]: TwoCent
        [2]: FiveCent
        [3]: TenCent
        [4]: 22
        [5]: 50
        [6]: 100
        [7]: 296
        [8]: 598
        [9]: 1298
        [10]: 4132
        [11]: 8264
        [12]: 16534

前四个是正确的,但显然那些int值(从索引4开始)并不对应于枚举&#39;值。

为什么我会得到那些奇怪的价值?

2 个答案:

答案 0 :(得分:2)

0X16是hexadecimal值,等于1 * 16 + 6 = 22.

类似地,

0x32 = 3 * 16 + 2 = 50

0x64 = 6 * 16 + 4 = 100,依此类推。

尝试将十六进制值更改为十进制值,即

[Flags]
public enum CoinSizes
{
    [Display(Name = "0.01")]
    OneCent = 1,
    [Display(Name = "0.02")]
    TwoCent = 2,
    [Display(Name = "0.05")]
    FiveCent = 4,
    [Display(Name = "0.10")]
    TenCent = 8,
    [Display(Name = "0.20")]
    TwentyCent = 16,
    [Display(Name = "0.25")]
    TwentyFiveCent = 32,
    [Display(Name = "0.50")]
    FiftyCent = 64,
    [Display(Name = "1.00")]
    OneDollar = 128,
    [Display(Name = "2.00")]
    TowDollar = 256,
    [Display(Name = "5.00")]
    FiveDollar = 512,
    [Display(Name = "10.00")]
    TenDollar = 1024,
    [Display(Name = "25.00")]
    TwentyFiveDollar = 2048,
    [Display(Name = "50.00")]
    FiftyDollar = 4096
}

Flags枚举用于碰撞值是不明智的。如果使用,Oring或ANDing会产生不希望的结果。

答案 1 :(得分:1)

使用十六进制代码返回的值是正确的。所以0x16是22.因为1 * 16 + 6是22.另外对于像0x64这样的其他值是100。

相关问题