0
0

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#] FlagsとHasFlagの仕様の確認

Last updated at Posted at 2023-09-14

やりたいこと

  • 変数flagが、複数のフラグのどれか一つでも持っていればTrueにしたい

検証

[Flags]
enum F {
	A = 1 << 0,
	B = 1 << 1,
	C = 1 << 2,
};
F flag = F.A;
Console.WriteLine($"{flag.HasFlag(F.A)}"); // True
Console.WriteLine($"{flag.HasFlag(F.B)}"); // False
Console.WriteLine($"{flag.HasFlag(F.A|F.B)}"); // False ← こう書ければ楽だった

flag = F.A|F.B;
Console.WriteLine($"{flag.HasFlag(F.A|F.B)}"); // True

flag = F.A|F.B|F.C;
Console.WriteLine($"{flag.HasFlag(F.A|F.B)}"); // True

結論

  • 普通にビット演算
Console.WriteLine($"{(flag & (F.A|F.B))>0}");
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?