假设我们有一个具有FlagsAttribute的enum。
[Flags]
enum CarOptions
{
Sunroof = 1,
Spoiler = 2,
TintedWindow = 4
}这可以很容易地使用。现在假设这一条
[Flags]
enum CarOptions
{
SunroofElectrical,
SunroofMechanical,
Spoiler,
TintedWindowBlack,
TintedWindowPurple
}当然,这在语法上是不正确的。但一辆车不能同时有机械和电气的天窗,也不能同时有黑色和紫色的TintedWindow。
问题是:是否有一种机制来实现不能同时具有某些属性的Flags枚举?
发布于 2011-01-10 18:53:07
这方面没有内置的机制。标志枚举允许组合成员的任意组合。在这种情况下,您将需要执行手动验证,或者创建一个不接受无效选项的模型。还有其他选择,但我选择的首选方法类似于:
class CarOptions
{
public SunroofKind Sunroof { get; set; }
public SpoilerKind Spoiler { get; set; }
public TintedWindowKind TintedWindow { get; set; }
// Note that I split this into two enums - the kind of tinted window
// (UV-resistant option too maybe?) and color might be different.
// This is just an example of how such option composition can be done.
public TintedWindowColor TintedWindowColor { get; set; }
// In this class, you can also implement additional logic, such as
// "cannot have spoiler on diesel engine models" and whatever may be required.
}
enum SunroofKind
{
None,
Electrical,
Mechanical
}
enum SpoilerKind
{
None,
Standard
}
enum TintedWindowKind
{
None,
Standard
}
enum TintedWindowColor
{
Black,
Blue
}如您所见,我完全摆脱了原始的枚举。我看不出有任何理由在这个场景中使用这样的构造--也需要应用特定于领域的组合逻辑的不同变量的组合不是标志枚举的良好候选者。选项和逻辑应该封装在一个类中(或者可能是一个结构,这取决于它的使用方式)。
标志枚举只在非常简单和/或特殊的情况下才有用。
发布于 2011-01-10 18:29:48
我猜你会通过使用不同的枚举来实现这一点,比如Sunroofs和TindedWindows。
发布于 2011-01-10 18:30:14
在我看来,你有两个选择:
1)不要使用enum。使用另一种机制来设置相互冲突的组合选项。
2)定义无效组合,并在设置标志时检查:
[flags]
enum CarOptions
{
SunroofElectrical = 1,
SunroofMechanical = 2,
Spoiler = 4,
TintedWindowBlack = 8,
TintedWindowPurple= 16,
// bad combos
BadSunroof = 3,
BadWindowColor = 24
}
CarOptions opt = CarOptions.SunroofElectrical | CarOptions.SunroofMechanical;
if(opt & BadSunroof)
{
}https://stackoverflow.com/questions/4645718
复制相似问题