[英]Switch on enum with Flags
I have the following enum 我有以下枚举
[Flags]
public enum Anchor
{
None = 1,
Top = 2, Bottom = 4,
Left = 8, Right = 16
}
I need to test every possible combination of Top, Bottom, Left and Right but declaring all those combinations in a switch is awful. 我需要测试“上”,“下”,“左”和“右”的每种可能组合,但是在开关中声明所有这些组合是糟糕的。
switch (anchor)
{
case Anchor.Left:
Thing1();
break;
case Anchor.Top:
Thing2();
break;
case Anchor.Left | Anchor.Top:
Thing3();
break;
}
This question is not a duplicate of this or this . 这个问题不是this或this的重复。 I've tried both solutions and neither works for me because if my enum is, say
Anchor.Left | Anchor.Top
我已经尝试了两种解决方案,但都没有用,因为如果我的枚举是,例如
Anchor.Left | Anchor.Top
Anchor.Left | Anchor.Top
, Thing1()
and Thing2()
would be called whereas I need Thing3()
to be called. Anchor.Left | Anchor.Top
, Thing1()
和Thing2()
,而我需要Thing3()
。
Declare all these combinations in a switch. 在开关中声明所有这些组合。 (as you started)
(开始时)
Its clear, understandable, maintainable. 其清晰,可理解,可维护。
Not awful. 不可怕 (Feels just a bit stupid to key it in)
(感觉有点愚蠢将其键入)
After all, you have these distict cases, so a switch is the perfect construction. 毕竟,您拥有这些截然不同的案例,因此开关是完美的构造。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.