按位标志和 Switch 语句?
我有以下代码(示例),我真的对这么多“if”检查感到不舒服:
public enum Flags
{
p1 = 0x01, // 0001
p2 = 0x02, // 0010
p3 = 0x04, // 0100
p4 = 0x08 // 1000
};
public static void MyMethod (Flags flag)
{
if ((flag & Flags.p1) == Flags.p1)
DoSomething();
if ((flag & Flags.p2) == Flags.p2)
DosomethingElse();
if ((flag & Flags.p3) == Flags.p3)
DosomethingElseAgain();
if ((flag & Flags.p4) == Flags.p4)
DosomethingElseAgainAndAgain();
}
MyMethod(Flags.p1 | Flags.p3);
有什么方法可以使用“switch”语句。也许如果我将它们转换为字符串,或者使用数组?
I have the following code (example), and I'm really not comfortable with so many 'if' checks:
public enum Flags
{
p1 = 0x01, // 0001
p2 = 0x02, // 0010
p3 = 0x04, // 0100
p4 = 0x08 // 1000
};
public static void MyMethod (Flags flag)
{
if ((flag & Flags.p1) == Flags.p1)
DoSomething();
if ((flag & Flags.p2) == Flags.p2)
DosomethingElse();
if ((flag & Flags.p3) == Flags.p3)
DosomethingElseAgain();
if ((flag & Flags.p4) == Flags.p4)
DosomethingElseAgainAndAgain();
}
MyMethod(Flags.p1 | Flags.p3);
Is there some way, that i could use an 'switch' statement. Maybe if I convert them to strings, or use arrays?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像这样的东西吗?
编辑:如果操作顺序很重要,则可能需要
OrderBy
子句。Something like this?
EDIT: If the order of actions are important, an
OrderBy
clause may be required.这是 Ani 的答案的一个变体:
这里重要的区别是它迭代枚举中定义的值而不是字典中的条目。这样,如果您将新标志添加到枚举而不将其添加到字典中,那么当您尝试使用新标志时,您将收到异常。它总是按照标志的顺序迭代。
Here's a variation on Ani's answer:
The important difference here is that it iterates over the defined values in the enumeration rather than the entries in the dictionary. That way if you add a new flag to the enum without adding it to the dictionary, you will get an exception when you try to use the new flag. And it always iterates in order of the flags.