Note that there are some explanatory texts on larger screens.

plurals
  1. PORemove privilege enum flags the right way in C#
    primarykey
    data
    text
    <p>I have an enum type for user privileges that looks like this:</p> <pre><code>[Flags] public enum UserPrivileges : byte { None = 0, // 0000 0000 View = 1 &lt;&lt; 0, // 0000 0001 Import = 1 &lt;&lt; 1, // 0000 0010 Export = 1 &lt;&lt; 2, // 0000 0100 Supervisor = View | Import | Export | 1 &lt;&lt; 3, // 0000 1111 Admin = Supervisor | 1 &lt;&lt; 4 // 0001 1111 } </code></pre> <p>These values are bound to CheckBoxes in the GUI with a value converter. (I wanted to do this as generic as possible because there are also different privileges [e.g. EmployeePrivileges])</p> <pre><code>public class ByteFlagsEnumValueConverter : IValueConverter { private byte _targetValue; public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var mask = (byte)parameter; _targetValue = (byte)value; return ((mask | _targetValue) == _targetValue); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { var mask = (byte)parameter; if ((bool)value) { _targetValue |= mask; } else { // Get next superflag for mask (e.g. 0110 -&gt; 1111) var b = mask; b--; b |= (byte)(b &gt;&gt; 1); b |= (byte)(b &gt;&gt; 2); b |= (byte)(b &gt;&gt; 4); b |= (byte)(b &gt;&gt; 8); // if you remove a superflag (e.g. 1111) also remove // everything higher than this flag if (mask == b || mask == 1) _targetValue &amp;= (byte)(mask &gt;&gt; 1); else // ???????? } return Enum.Parse(targetType, _targetValue.ToString()); } } </code></pre> <p>This works really fine for displaying and adding privileges to the user in the GUI. Also it works for removing Superflags like Supervisor (all flags <code>&gt;=</code> Supervisor get removed, the other flags don't change).</p> <p>The problem is when I uncheck Import for example, I want to remove all Superflags (Supervisor, Admin) but would like to keep the other flags (View, Export).</p> <pre><code>0001 1111 // Admin 0000 0010 // Import --------- 0000 0101 // View | Export </code></pre> <p>But I haven't come up with an good idea how to accomplish this. Anyboy who has a good solution for this?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload