你能在 C# 中循环遍历枚举吗?

发布于 2024-12-07 13:35:01 字数 132 浏览 4 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

昨迟人 2024-12-14 13:35:01

您应该能够利用以下内容:

foreach (MY_ENUM enumValue in Enum.GetValues(typeof(MY_ENUM)))
{
   // Do work.
}

You should be able to utilize the following:

foreach (MY_ENUM enumValue in Enum.GetValues(typeof(MY_ENUM)))
{
   // Do work.
}
段念尘 2024-12-14 13:35:01

看一下 Enum.GetValues< /a>:

foreach (var value in Enum.GetValues(typeof(MY_ENUM))) { ... }

Take a look at Enum.GetValues:

foreach (var value in Enum.GetValues(typeof(MY_ENUM))) { ... }
无人接听 2024-12-14 13:35:01

枚举有点像整数,但您不能依赖它们的值始终是连续的或升序的。您可以将整数值分配给枚举值,这会破坏简单的 for 循环:

public class Program
{
    enum MyEnum
    {
        First = 10,
        Middle,
        Last = 1
    }

    public static void Main(string[] args)
    {
        for (int i = (int)MyEnum.First; i <= (int)MyEnum.Last; i++)
        {
            Console.WriteLine(i); // will never happen
        }

        Console.ReadLine();
    }
}

正如其他人所说,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:

public class Program
{
    enum MyEnum
    {
        First = 10,
        Middle,
        Last = 1
    }

    public static void Main(string[] args)
    {
        for (int i = (int)MyEnum.First; i <= (int)MyEnum.Last; i++)
        {
            Console.WriteLine(i); // will never happen
        }

        Console.ReadLine();
    }
}

As others have said, Enum.GetValues is the way to go instead.

肥爪爪 2024-12-14 13:35:01

public static Array GetValues(Type enumType) 方法返回一个包含 anEnum 枚举值的数组。由于数组实现了 IEnumerable 接口,因此可以枚举它们。
例如:

 EnumName[] values = (EnumName[])Enum.GetValues(typeof(EnumName));
 foreach (EnumName n in values) 
     Console.WriteLine(n);

您可以在 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 :

 EnumName[] values = (EnumName[])Enum.GetValues(typeof(EnumName));
 foreach (EnumName n in values) 
     Console.WriteLine(n);

You can see more detailed explaination at MSDN.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文