【问题标题】:Enumeration issue when using Flag attribute使用标志属性时的枚举问题
【发布时间】:2019-06-12 13:11:55
【问题描述】:

我有以下枚举:

[Flags]
public enum ElementsTag
{
    None,
    Surname,
    SecondSurname,
    Forenames,
    PersonalNumber,
    Birthday,
    Nationality,
    DocumentExpirationDate,
    DocumentNumber,
    Sex,
    CityOfBirth,
    ProvinceOfBirth,
    ParentsName,
    PlaceOfResidence,
    CityOfResidence,
    ProvinceOfResidence
}

所以,当我尝试将枚举值作为参数传递给方法时,如下所示:

this.GetDataElementFromByteArray((byte[])aData, ElementsTag.ParentsName);

我可以在调试中看到 ElementsTag.ParentsName 包含值:

PersonalNumber | DocumentNumber 

而不是只包含父母姓名。枚举的其他成员也会发生这种情况,例如,传递给方法 ElementsTag.Nationality 包含:

Nationality = SecondSurname | PersonalNumber

为什么?

我希望每个枚举成员只包含自己的值而不包含其他值,例如:

ElementsTag.ParentsName = ParentsName
ElementsTag.Nationality = Nationality

如何做到这一点?

【问题讨论】:

    标签: c# enums visual-studio-2008 .net-3.5 enumeration


    【解决方案1】:

    你的枚举定义等于这个

    [Flags]
    public enum ElementsTag
    {
        None = 0,
        Surname = 1,
        SecondSurname = 2,
        Forenames = 3,
        PersonalNumber = 4,
        Birthday = 5,
        Nationality = 6,
        DocumentExpirationDate = 7,
        DocumentNumber = 8,
        Sex = 9,
        CityOfBirth = 10,
        ProvinceOfBirth  = 11,
        ParentsName = 12,
        PlaceOfResidence = 13,
        CityOfResidence = 14,
        ProvinceOfResidence = 15
    }
    

    如果传递ElementsTag.ParentsName,则使用值 12。在二进制表示法中 12 = 0000 1100。因此设置了第 3 位和第 4 位。第 3 位对应值 4,即ElementsTag.PersonalNumber,第 4 位是值 8,对应ElementsTag.DocumentNumber

    如果您想要独特的值,则必须使用 2^n 值,如下所示:

    [Flags]
    public enum ElementsTag
    {
        None = 0,
        Surname         = 1,
        SecondSurname   = 1 << 1, // 2
        Forenames       = 1 << 2,  // 4
        PersonalNumber  = 1 << 3, // 8
        Birthday        = 1 << 4,
        Nationality     = 1 << 5,
        DocumentExpirationDate = 1 << 6,
        DocumentNumber         = 1 << 7,
        Sex                    = 1 << 8,
        CityOfBirth            = 1 << 9,
        ProvinceOfBirth        = 1 << 10,
        ParentsName            = 1 << 11,
        PlaceOfResidence       = 1 << 12,
        CityOfResidence        = 1 << 13,
        ProvinceOfResidence    = 1 << 14
    }
    

    【讨论】:

    • 最好使用1 &lt;&lt; n 表示法,而不是显式计算两个的每个幂,例如Birthday = 16 会变成Birthday = 1 &lt;&lt; 4Nationality = 32 会变成Nationality = 1 &lt;&lt; 5,等等
    • @Iridium:感谢您提供的信息。我已经更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-14
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多