1
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 5 years have passed since last update.

enumの複数判定を少し簡潔に書けたらいいな

Posted at

※Switch文とか 可読性とか とりあえず置いといて

enumでフラグを用意すると

enum HOGE
{
  A,
  B,
  C
}

HOGE SuperUltraBigMaximGreatStrongHoge;

if (SuperUltraBigMaximGreatStrongHoge == HOGE.A ||
    SuperUltraBigMaximGreatStrongHoge == HOGE.B ||
    SuperUltraBigMaximGreatStrongHoge == HOGE.C
    )
{
  // HogeHoge-
}

と、SuperUltraBigMaximGreatStrongHogeを何度も書くのはチョット…
1行で簡潔に書きたいなーと。
(サジェスチョンとか補完で打つのはツラくはなさそうですが)

まず、Enum拡張を書く。

public static class HogeEnumExtensions
{
  /// <summary>論理積</summary>
  public static bool and(this HOGE m, HOGE f) => (m & f) == f;
  /// <summary>論理和</summary>
  public static bool or(this HOGE x, HOGE f) => (x & f) != 0;
  /// <summary>否定論理和</summary>
  public static bool nor(this HOGE x, HOGE f) => (x & f) == 0;
}

で、HOGEをpublic・Flags指定する。

[Flags]
public enum HOGE
{
  A = 0b0001,
  B = 0b0010,
  C = 0b0100,
}

HOGE SuperUltraBigMaximGreatStrongHoge;

if (SuperUltraBigMaximGreatStrongHoge.or(HOGE.A | HOGE.B | HOGE.C))
{
  // HogeHoge-
}

こういう書き方もあるよー的に。
…アセンブラみたいな書き方ですね

1
1
2

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
1
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?