开发者

Can you loop through an enum in C#?

开发者 https://www.devze.com 2023-04-09 08:53 出处:网络
for (int i = (int)MY_ENUM.First; i <= (int)MY_ENU开发者_如何学编程M.Last; i++) { //do work } Is there a more elegant way to do this?You should be able to utilize the following:
for (int i = (int)MY_ENUM.First; i <= (int)MY_ENU开发者_如何学编程M.Last; i++)
{
    //do work
}

Is there a more elegant way to do this?


You should be able to utilize the following:

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


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.


Take a look at Enum.GetValues:

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号