是否可以让枚举自动生成其值
来自 MSDN 上的此示例:
[Flags]
public enum Pet {
None = 0,
Dog = 1,
Cat = 2,
Bird = 4,
Rabbit = 8,
Other = 16
}
无论如何,有没有让枚举自动生成其值?
From this sample on MSDN:
[Flags]
public enum Pet {
None = 0,
Dog = 1,
Cat = 2,
Bird = 4,
Rabbit = 8,
Other = 16
}
Is there anyway to let the enum generates its values automatically ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您确实想要一个“flags”枚举,则没有自动方法可以做到这一点,不。
Pet
示例似乎不太适合标志,但我假设这只是一个不幸的示例选择。稍微降低错误可能性的一种选择是使用位运算:如果一切都使用位移位,您就知道您不会意外地得到一个实际上是多个位的值。
Assuming that you really want a "flags" enum, there's no automated way of doing this, no. The
Pet
example doesn't seem like a good fit for flags, but I'm assuming that's just an unfortunate choice of example. One option which reduces the possibility for error slightly is to use bit operations:If everything uses bit shifting, you know you won't accidentally end up with a value which is actually multiple bits.
只是不要输入等号和值。
例如,
MSDN 网站上的示例之一 ( http://msdn.microsoft.com/en-us/library/sbbt4032(v=vs.80).aspx)
Just don't put in the equals sign and the value.
For exmaple,
is one of the examples on the MSDN website ( http://msdn.microsoft.com/en-us/library/sbbt4032(v=vs.80).aspx )
是的,把它们放在一边:
但是这样你就不应该用 flags 属性来装饰枚举,因为这些值不能再以有意义的方式组合起来。
Yes, just leave them away:
But this way you should not decorate the enum with the flags attribute because the values cannot be combined anymore in a meaningful way.