5

私のGUIには6つのボタンがあります。ボタンの表示は、チェックボックスで構成できます。チェックボックスをオンにして保存すると、対応するボタンが表示されます。6つのボタンすべての可視性を表すTinyInt列をデータベースに1つ持つことが何とか可能かどうか疑問に思っています。

ボタンの列挙型を作成しました。次のようになります。

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

ここで、たとえば、この 1 つの列を使用してボタン 1、ボタン 5、およびボタン 6 のみがチェックされると言う方法を考えています。まったく可能ですか?

ありがとう :-)

4

3 に答える 3

6

代わりに flags 列挙型を使用します。

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

次に、ボタンの任意の組み合わせも一意の値です。たとえば、ボタン 1 & ボタン 3 == 5 です。

値を設定するときは、二項「または」演算子 (|) を使用します。

MyButtons SelectedButtons = MyButtons.Button1 | MyButtons.Button3

ボタンが選択されているかどうかを調べるには、2 項「and」演算子 (&) を使用します。

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

これが機能する理由は、数値のバイナリ表現を考えると明らかになります。

MyButtons.Button1 = 000001
MyButtons.Button3 = 000100

それらを一緒に「または」すると、

SelectedButtons = 000001 | 000100 = 000101

MyButtons.Button1 でそれを「and」すると、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 に答える