2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C#でEnumをFlagとして使用する

Last updated at Posted at 2023-07-24

1. はじめに

  • C#でEnumにFlag属性を追加して複数選択を判別したい
  • 1つのEnum値で2進数のビット情報で複数の選択状態を管理してみたい

2. 開発環境

  • C#
  • .Net 6
  • Visual Studio 2022
  • Windows 11

3. Enumクラス

  • EnumクラスにFlag属性を追加する
  • Enumの数値は2進数で記載し、ビットの桁位置が被らないようにする
SelectItemEnum.cs
[Flags]
public enum SelectItemEnum
{
    // 「0b」から始めると2進数で書ける
    AAA = 0b0001,

    BBB = 0b0010,

    CCC = 0b0100
}

4. 動作確認

  • 想定通り動いた
    image.png
Form1.cs
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // int flag = 1;    // 0b0001:AAA選択
        // int flag = 2;    // 0b0010:BBB選択
        // int flag = 3;    // 0b0011:AAA,BBB選択
        // int flag = 4;    // 0b0100:CCC選択
        // int flag = 5;    // 0b0101:AAA,CCC選択
        // int flag = 6;    // 0b0111:BBB,CCC選択
        int flag = 7;    // 0b0111:全件選択

        // int → Enumへ変換
        SelectItemEnum enums = (SelectItemEnum)a;

        // 選択状態を確認
        foreach (SelectItemEnum value in Enum.GetValues(typeof(SelectItemEnum)))
        {
            if (enums.HasFlag(value))
            {
                // 選択した値をコンボボックスへ追加
                comboBox1.Items.Add(value);
                comboBox1.SelectedIndex = 0;
            }
        }

    }
}

5. 参考文献

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?