你能在 C# 中循环遍历枚举吗?
for (int i = (int)MY_ENUM.First; i <= (int)MY_ENUM.Last; i++)
{
//do work
}
有没有更优雅的方法来做到这一点?
for (int i = (int)MY_ENUM.First; i <= (int)MY_ENUM.Last; i++)
{
//do work
}
Is there a more elegant way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该能够利用以下内容:
You should be able to utilize the following:
看一下
Enum.GetValues
< /a>:Take a look at
Enum.GetValues
:枚举有点像整数,但您不能依赖它们的值始终是连续的或升序的。您可以将整数值分配给枚举值,这会破坏简单的
for
循环:正如其他人所说,
Enum.GetValues
是正确的选择。Enums are kind of like integers, but you can't rely on their values to always be sequential or ascending. You can assign integer values to enum values that would break your simple
for
loop:As others have said,
Enum.GetValues
is the way to go instead.public static Array GetValues(Type enumType)
方法返回一个包含 anEnum 枚举值的数组。由于数组实现了 IEnumerable 接口,因此可以枚举它们。例如:
您可以在 MSDN 中查看更详细的说明。
The
public static Array GetValues(Type enumType)
method returns an array with the values of the anEnum enumeration. Since arrays implements the IEnumerable interface, it is possible to enumerate them.For example :
You can see more detailed explaination at MSDN.