Combining Enums

后端 未结 5 1649
旧巷少年郎
旧巷少年郎 2021-02-03 22:45

Is there a way to combine Enums in VB.net?

5条回答
  •  耶瑟儿~
    2021-02-03 23:31

    You can use the FlagsAttribute to decorate an Enum like so which will let you combine the Enum:

     _
    Public Enumeration SecurityRights
    None = 0
    Read = 1
    Write = 2
    Execute = 4
    

    And then call them like so (class UserPriviltes):

    Public Sub New ( _
        options As SecurityRights _
    )
    
    New UserPrivileges(SecurityRights.Read OR SecurityRights.Execute)
    

    They effectively get combined (bit math) so that the above user has both Read AND Execute all carried around in one fancy SecurityRights variable.

    To check to see if the user has a privilege you use AND (more bitwise math) to check the users enum value with the the Enum value you're checking for:

    //Check to see if user has Write rights
    If (user.Privileges And SecurityRights.Write = SecurityRigths.Write) Then
        //Do something clever...
    Else
        //Tell user he can't write.
    End If
    

    HTH, Tyler

提交回复
热议问题