加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用FlagsAttributes进行枚举

发布时间:2020-12-16 01:40:13 所属栏目:百科 来源:网络整理
导读:假设我们有一个包含FlagsAttribute的枚举. [Flags]enum CarOptions{ Sunroof = 1,Spoiler = 2,TintedWindow = 4} 这可以很容易地使用. 现在假设这个 [Flags]enum CarOptions{ SunroofElectrical,SunroofMechanical,Spoiler,TintedWindowBlack,TintedWindowPu
假设我们有一个包含FlagsAttribute的枚举.

[Flags]
enum CarOptions
{
  Sunroof = 1,Spoiler = 2,TintedWindow = 4
}

这可以很容易地使用.
现在假设这个

[Flags]
enum CarOptions
{
  SunroofElectrical,SunroofMechanical,Spoiler,TintedWindowBlack,TintedWindowPurple
}

当然这在语法上是不正确的.但是,汽车不能同时拥有机械和电动天窗,也不能同时拥有黑色和紫色的TintedWindow.
问题是:是否有一种机制来实现Flags枚举,它不能同时具有某些属性?

解决方法

没有内置的机制.标记枚举允许组合成员的任何组合.您需要在这种情况下执行手动验证,或创建不接受无效选项的模型.还有其他选择,但我选择的首选方法与此类似:

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
}

如你所见,我完全摆脱了原来的枚举.在这种情况下,我没有看到任何理由使用这样的构造 – 也需要应用特定于域的组合逻辑的不同变量的组合不是标记枚举的良好候选者.选项和逻辑应该封装在一个类中(或者可能是一个结构体,具体取决于它的使用方式).

标记枚举仅对非常简单和/或特殊情况有用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读