为什么标志枚举通常定义与十六进制值 [英] Why are flag enums usually defined with hexadecimal values

查看:1913
本文介绍了为什么标志枚举通常定义与十六进制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很多时候,我看到使用十六进制值标志枚举声明。例如:

A lot of times I see flag enum declarations that use hexadecimal values. For example:

[Flags]
public enum MyEnum
{
    None  = 0x0,
    Flag1 = 0x1,
    Flag2 = 0x2,
    Flag3 = 0x4,
    Flag4 = 0x8,
    Flag5 = 0x10
}

当我宣布一个枚举,我通常声明它是这样的:

When I declare an enum, I usually declare it like this:

[Flags]
public enum MyEnum
{
    None  = 0,
    Flag1 = 1,
    Flag2 = 2,
    Flag3 = 4,
    Flag4 = 8,
    Flag5 = 16
}

有,为什么有些人选择写在十六进制而不是十进制值的原因或理由是什么?我看到它的方式,它更容易感到困惑,用十六进制值时,不小心写 Flag5 =为0x16 ,而不是 Flag5 = 0×10

推荐答案

理论基础可能会有所不同,但我看到的好处是,十六进制提醒您:好吧,我们不能与数字打交道的任意人类发明的世界。十进制了我们正在处理的比特 - 计算机的世界 - 我们要发挥它的规则。十六进制很少使用,除非你正在处理的比较低级的主题数据问题,其中的内存布局。使用它暗示的是,这是我们在现在的情况。

Rationales may differ, but an advantage I see is that hexadecimal reminds you: "Okay, we're not dealing with numbers in the arbitrary human-invented world of base ten anymore. We're dealing with bits - the machine's world - and we're gonna play by its rules." Hexadecimal is rarely used unless you're dealing with relatively low-level topics where the memory layout of data matters. Using it hints at the fact that that's the situation we're in now.

此外,我不知道C#,但我知道,在C X<<是是一个有效的编译时间常数。 使用移位似乎是最明确的:

Also, i'm not sure about C#, but I know that in C x << y is a valid compile-time constant. Using bit shifts seems the most clear:

[Flags]
public enum MyEnum
{
    None  = 0,
    Flag1 = 1 << 0,
    Flag2 = 1 << 1,
    Flag3 = 1 << 2,
    Flag4 = 1 << 3,
    Flag5 = 1 << 4
}

这篇关于为什么标志枚举通常定义与十六进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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