【问题标题】:Use TinyInt to hide/show controls?使用 TinyInt 隐藏/显示控件?
【发布时间】:2011-02-23 15:06:34
【问题描述】:

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

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

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

现在我想知道如何使用这一列检查例如仅按钮 1、按钮 5 和按钮 6。有可能吗?

谢谢:-)

【问题讨论】:

  • 为什么不接受马丁的回答?

标签: c# enums visibility tinyint


【解决方案1】:

改用标志枚举:

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

那么按钮的任何组合也是一个唯一值 - 例如按钮 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

【讨论】:

  • 听起来不错,我该如何保存?我的意思是,该列是一个 tinyint,如何在保存之前设置所有按钮?
  • MSDN建议下一步:使用None作为值为0的标志枚举常量的名称。msdn.microsoft.com/ru-ru/library/system.flagsattribute.aspx
  • 获得 SelectedButtons 值后,只需将其转换为 int 并将其保存到数据库中。当您将其从数据库中取出时,将其转换回 MyButtons 枚举值。在 Enum 类上有一些静态方法可以做到这一点 (msdn.microsoft.com/en-us/library/system.enum_members.aspx)
  • 还要考虑到 tinyint 的最大值为 255(8 位),因此如果您有超过 8 个按钮,则需要更大的列类型。
【解决方案2】:

你必须用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;

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

【讨论】:

    【解决方案3】:

    添加 FlagsAttribute,并从 byte 派生枚举:

    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
    } 
    

    【讨论】:

    • 还有一件事:从数据库中检索到 1 和 0 后,我怎么知道它是什么? --> 找到了解决方案...参见 Martin Harris 的帖子 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-22
    • 2012-07-19
    • 2011-12-24
    • 1970-01-01
    • 1970-01-01
    • 2018-01-14
    相关资源
    最近更新 更多