作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
假设我在标志和非标志变体中都需要一个枚举。
选项 1:我可以复制所有内容:
enum Color { Red, Blue, Green }
[Flags]
enum Colors {
None = 0,
Red = 1,
Blue = 2,
Green = 4
}
// use cases
Color currentColor;
Colors supportedColors;
选项 2:我可以对所有内容使用 Flags 变体:
Colors currentColor; // ugly, since neither "None" nor "Red | Blue" should be valid
我不喜欢其中任何一个:在选项 1 中,Color.Red
和 Colors.Red
完全无关,这可能需要绑定(bind)代码。此外,我必须使两个枚举保持同步。选项 2 的缺点是显而易见的。我真正想要的是
enum Colors = Flag set of Color;
是否有针对此要求的更优雅的解决方案?
最佳答案
我会简单地对所有内容使用 [Flags]
版本,并简单地确保在几个地方它只是一个值。无论哪种方式,您需要都这样做,因为即使没有[Flags]
,以下内容也是有效的:
var flags = (Color)47; // why not
所以您需要检查 Color
是否是您所期望的无论如何。 [Flags]
只会帮助序列化/解析。
关于c# - 枚举的标志和非标志变体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9016453/
我是一名优秀的程序员,十分优秀!