简体   繁体   中英

Using Enum Flags How to?

Currently I have 4 permissions in my website

Edit
Delete
Add
View

Everyone gets view permissions when someone subscribes to someone else.

Currently in I store each as a column in my database as a bit value.

I am thinking maybe I should use enum with flags but I have some questions.

  1. The user will be able to choose the users permissions(eveyone gets view you cannot take that away). Right now it is easy as I use a checkbox and then save the bool value to the db.

My questions is what is the best way to convert checkboxes to the enum type? So if they choose add permission I can map that to the right enum type.

Wondering if there is a better way then

PermissionTypes t;
if(add == true)
{
   t = PermissionTypes.Add
}

if(edit == true)
{
   t += PermissionTypes.Edit // not sure if you even can do this.
}

I know with enum flags you can use the pipe and do something like this

PermissionTypes t = PermissionTypes.Add | PermissionTypes.Edit

I am wondering is it good practice to have another type in my enum like

AddEdit = Add | Edit

I am thinking that can result in many combinations(imagine if I had like 10 permissions or something like that).

Enums are simply integers values. By settings your enum values to different power of 2, you can easily have any combination you need:

enum ePermissions
{

   None = 0,
   View = 1,
   Edit = 2,
   Delete = 4,
   Add = 8,
   All = 15
}

ePermissions t;
t = (ePermissions)((add?ePermissions.Add:ePermissions.None) | (delete?ePermissions.Delete:ePermissions.None) | ...);

if you want to know if some user has the Add permission just do as follow:

canAdd = (currentPermission & ePermissions.Add) != 0;

On converting set of bool values to enum - for small set if would be ok. You can also use ?: operator to do the same in smaller number of lines:

[Flags]
enum Permissions 
{ 
   None = 0, 
   View = 1, 
   Edit = 2, 
   Delete = 4, 
   Add = 8, 
}

var permissions = 
  (add ? Permissions.Add : Permissions.None) |
  (edit ? Permissions.Edit : Permissions.None) |
  (delete ? Permissions.Delete : Permissions.None);

If you have large number of values some sort of mapping of Control to Enum may be useful.

On AddEdit - this particular on is probably not useful. You can as easily write Add | Edit Add | Edit . Some menaingful combinations of permissions (or falgs) may be named specifically if code will use such combination in meanigfull way. Ie CanModify = Add | View CanModify = Add | View .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM