5

我的 GUI 上有 6 个按钮。可以通过复选框配置按钮的可见性。选中复选框并保存意味着应该显示相应的按钮。我想知道是否有可能在数据库中有一个 TinyInt 列,它代表所有 6 个按钮的可见性。

我为按钮创建了一个枚举,它看起来像这样:

public enum MyButtons
{
    Button1 = 1,
    Button2 = 2,
    Button3 = 3,
    Button4 = 4,
    Button5 = 5,
    Button6 = 6
}

现在我想知道怎么说,例如,使用这一列只检查了 button1、button5 和 button6。有可能吗?

谢谢 :-)

4

3 回答 3

6

改为使用标志枚举:

[Flags]
public enum MyButtons
{
    None = 0
    Button1 = 1,
    Button2 = 2,
    Button3 = 4,
    Button4 = 8,
    Button5 = 16,
    Button6 = 32
}

那么按钮的任何组合也是一个唯一值 - 例如 Button 1 & Button3 == 5

设置值时使用二进制“或”运算符 (|):

MyButtons SelectedButtons = MyButtons.Button1 | MyButtons.Button3

要确定是否选择了按钮,请使用二进制“和”运算符 (&):

if (SelectedButtons & MyButtons.Button1 == MyButtons.Button1)... 

当您考虑数字的二进制表示时,其工作原理变得显而易见:

MyButtons.Button1 = 000001
MyButtons.Button3 = 000100

当你“或”他们在一起时,你会得到

SelectedButtons = 000001 | 000100 = 000101

当您使用 MyButtons.Button1 进行“和”时 - 您将返回 MyButtons.Button1:

IsButton1Selected = 000101 & 000001 = 000001
于 2010-05-25T10:23:53.823 回答
3

您必须使用以下标记您的枚举FlagsAttribute

[Flags]
public enum MyButtons : byte
{
    None = 0
    Button1 = 1,
    Button2 = 1 << 1, 
    Button3 = 1 << 2, 
    Button4 = 1 << 3, 
    Button5 = 1 << 4,
    Button6 = 1 << 5
}

所以你可以使用:

var mode = MyButtons.Button1 | MyButtons.Button5 | MyButtons.Button6;

<<表示“左移运算符” - 只是为枚举项设置值的更简单的方法。

于 2010-05-25T10:24:42.290 回答
1

添加 FlagsAttribute,并从字节派生枚举:

class Program {
    static void Main(string[] args) {
        MyButtons buttonsVisible = MyButtons.Button1 | MyButtons.Button2;
        buttonsVisible |= MyButtons.Button8;

        byte buttonByte = (byte)buttonsVisible; // store this into database

        buttonsVisible = (MyButtons)buttonByte; // retreive from database
    }
}

[Flags]
public enum MyButtons : byte {
    Button1 = 1,
    Button2 = 1 << 1,
    Button3 = 1 << 2,
    Button4 = 1 << 3,
    Button5 = 1 << 4,
    Button6 = 1 << 5,
    Button7 = 1 << 6,
    Button8 = 1 << 7
} 
于 2010-05-25T10:35:16.580 回答