[Flags]
public enum DriversLicenseFlags
{
None = 0,
Suspended = 1 << 1,
Revoked = 1 << 2,
Restored = 1 << 3,
SuspendedAndRestored = Suspended | Restored,
RevokedAndRestored = Revoked | Restored,
}
以下是我的意图:
Suspended
和Revoked
是独特的状态,可以但不一定会导致恢复。- 只有当用户也被
Suspended
或Revoked
(或两者都)时,才应该允许Restored
。重要的是要具体跟踪哪个事件是恢复的前提条件。 - 许可证可以同时被
Suspended
、Revoked
(和Restored
)
此外,我试图遵循 MSDN 的 Designing Flags Enumerations 中提出的建议,包括:
- 考虑为常用的标志组合提供特殊的枚举值。
SuspendedAndRestored
和RevokedAndRestored
都是常见的组合。
- 避免在某些值的组合无效时创建标志枚举。
- 这是我的问题,因为只有在至少设置了一个
Suspended
和Revoked
时,Restored
才是有效的。
- 这是我的问题,因为只有在至少设置了一个
理想情况下,我希望在枚举中为 Restored
提供一个值,以便在内部使用,但只能通过某些有效的组合公开设置。不幸的是,internal
不是枚举值的有效修饰符。
我想到了几个替代方案,但每个方案似乎都有缺点:
Keep
Restored
as a public value, note the limitations in comments and do a precondition check for invalid combinations on public APIs.This would work, and is likely the solution I will go with. However, it seems like their should be a cleaner solution.
Use an enhanced, java-like enum as described here and define
Restored
asinternal static
.This would also work, but feels like overkill because I don't need any of the other functionality at this point.
Don't define
Restored
as a value, but reserve the value for OR'ing, and for checking the value in consuming methods. i.e.:internal const int RestoredFlag = 1 << 3; [Flags] public enum DriversLicenseFlags { None = 0, Suspended = 1 << 1, Revoked = 1 << 2, SuspendedAndRestored = Suspended | RestoredFlag, RevokedAndRestored = Revoked | RestoredFlag, }
对我来说,这种方法感觉很不专业,无论是在定义方式上还是内部使用上。
SuspendedAndRevoked
和SuspendedAndRevokedAndRestored
。 - Jan