Counting the number of flags set on an enumeration

后端 未结 9 1312
孤街浪徒
孤街浪徒 2021-02-18 20:17

I\'m sure there must be a much better way of doing this. I\'m trying to do a count operation on a Flags enum. Before I was itterating over all the possible values and counting t

9条回答
  •  北荒
    北荒 (楼主)
    2021-02-18 21:00

    the only reason to use this method is if the flags are not contiguous and if flags will be added periodically.

     _
    Public Enum Skills As Integer
        Skill1 = CInt(2 ^ 0) 'bit 0
        Skill2 = CInt(2 ^ 1)
        Skill3 = CInt(2 ^ 2)
        Skill4 = CInt(2 ^ 3)
        Skill5 = CInt(2 ^ 4)
        Skill6 = CInt(2 ^ 5)
        Skill7 = CInt(2 ^ 6)
        Skill8 = CInt(2 ^ 7)
        Skillx = CInt(2 ^ 10) 'bit 10, some bits were skipped
    End Enum
    
    
        Dim mySkills As Integer = Skills.Skillx Or Skills.Skill4 Or Skills.Skill8 Or Skills.Skill6
        Dim count As Integer 'count of bits on
        count = CType(mySkills, Skills).ToString().Split(New Char() {","c}, _
                                                         StringSplitOptions.RemoveEmptyEntries).Count
    

    if "better" means faster this ain't ;) it.

提交回复
热议问题