使用 [Flags] 属性定义 C# 枚举的多种方法?
我了解枚举在 C# 中的工作原理,并且了解 Flags 属性给表带来的内容。
我在此处看到了这个问题。其中推荐第一种口味,但没有提供任何理由/理由。
这两者的定义方式是否存在差异,一个比另一个更好?使用第一个语法代替第二个有什么优点?在定义标志类型枚举时,我总是使用第二种风格......我一直都做错了吗?
[Serializable]
[Flags]
public enum SiteRoles
{
User = 1 << 0,
Admin = 1 << 1,
Helpdesk = 1 << 2
}
这不就是一样吗
[Serializable]
[Flags]
public enum SiteRoles
{
User = 1,
Admin = 2,
Helpdesk = 4
}
I understand how Enums work in C#, and I get what the Flags attribute brings to the table.
I saw this question, here. Which recommends the first flavor, but doesn't provide any reason/justification for it.
Is there a difference in the way in which these two are defined, is one better than the other? What are the advantages to using the first synax as instead of the second? I've always used the second flavor when defining Flags type Enums... have I been doing it wrong all this time?
[Serializable]
[Flags]
public enum SiteRoles
{
User = 1 << 0,
Admin = 1 << 1,
Helpdesk = 1 << 2
}
Is that not the same as
[Serializable]
[Flags]
public enum SiteRoles
{
User = 1,
Admin = 2,
Helpdesk = 4
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第一个的主要优点是您不需要计算每个标志的正确值,因为编译器会为您做这件事。除此之外,它们是相同的。
The main advantage with the first one is that you don't need to calculate the correct values for each flag since the compiler will do it for you. Apart from that they are the same.
考虑更复杂的示例:
此示例表明,在这种情况下,第一个版本的可读性要强得多。十进制文字并不是表示标志常量的最佳方式。有关按位运算(也可用于表示标志常量)的更多信息,请参阅 http://en。 wikipedia.org/wiki/Bitwise_operation
Consider more complex samples:
This samples shows that in this case first version is MUCH MORE readable. Decimal literals is not the best way to represent flag constants. And for more information about bitwise operations (that also can be used to represent flag constants) see http://en.wikipedia.org/wiki/Bitwise_operation
AFAIK 这是一场可读性辩论。有人会说第一个更具可读性,因为您在“<<”的右侧有标志的实际索引。
AFAIK its a readability debate. Some would say the first is more readable because you have the actual index of the flag on the right hand side of the '<<'.