一次性检查 3 个枚举值?
我有一个如下所示的枚举:
enum myEnum
{
field1 = 11,
field2 = 12,
field3 = 33
};
在我的代码中,根据我拥有的变量,我需要说 field1 是 1,field2 是 2,field3 是 3。该变量要么是 1,要么是 2,要么是 3;它是一个整数。我可以把它写成一行吗?类似于以下内容,但更短...
if(myVar == 1)
SomeMethod(myEnum.field1)
...
谢谢:-)
I have an enum which looks like this:
enum myEnum
{
field1 = 11,
field2 = 12,
field3 = 33
};
In my code I need to say that field1 is 1,field2 is 2 and field3 is 3 according to a variable I have. This variable is either 1 or 2 or 3; it's an int. Can I write that in one line? Something like the following, but shorter...
if(myVar == 1)
SomeMethod(myEnum.field1)
...
Thanks :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
编辑:想一想,您可能希望将其包装在
try/catch (ArgumentException)
中,以防万一myVar
的枚举中没有值> 给定,除非你能保证这永远不会发生。另一个编辑:想一想,如果只有三个值,你可以这样做:
但是,这会将 1 或 2 以外的任何值视为 3,但如果这是保证的,那么它应该不是问题。
Edit: Come to think of it, you probably want to wrap this in a
try/catch (ArgumentException)
just in case there isn't a value in the enum for themyVar
given, unless you can guarantee this will never happen.Another Edit: Thinking about it, if there's just three values, you could just do:
However, this treats any value other than 1 or 2 as if it was 3, but if this is guaranteed, it shouldn't be a problem.
如果我理解正确(如果没有,请扩展您的问题,因为它不是很清楚),您想做这样的事情:
If I understand you correctly (and if not, please extend your question as it is not very clear), you want to do something like this:
看起来 switch 语句比很多 if 更好。
Seems like a switch statement would be better than lots of ifs.
听起来您正在寻找的是位运算。通过将枚举定义为每个值仅设置一位,您可以执行一些有趣的操作,包括我认为您要问的操作。要定义像这样使用的枚举,您可以使用如下所示的内容:
初始化枚举值的语法可以让您轻松查看列表并看到恰好设置了一位,并且设置了 2 的所有幂。用过的。要检查多个值,您可以使用:
或者
myvar 是否为 int(与 C++ 不同,C# 需要显式转换为 int)。位运算一开始有点棘手,但经过一些练习,您应该能够弄清楚。
It sounds like what you are looking for is Bitwise Operations. By defining your enum to have only one bit set for each of the values, you can perform several interesting operations, including the one I think you are asking about. To define an enum to use like this you might use something like the following:
The syntax for initializing the values of the enum are there to make it easy to look at the list and see that exactly one bit is set and all powers of two are used. To check for multiple values you can use:
or
if myvar is an int (C# requires an explicit cast to int, unlike C++). Bitwise operations are a little tricky at first, but with a bit of practice you should be able to figure it out.
您是否尝试过对值使用 switch 语句而不是 if ?尝试此代码,它假定您在问题中声明的枚举类型。在 switch 语句中将 myVar 转换为 myEnum 类型,然后“viola!”即时映射!:
Have you tried using a switch statement instead of an if against the value? Try this code, which assumes the enumeration type that you've declared in your question. Cast myVar to an myEnum type in the switch statement and "viola!" instant mapping!:
另一种方式(请记住,当您使用 GetValues 时,枚举按其值排序):
Another way (bearing in mind the enum is sorted by its values when you use GetValues):