How can I enumerate everything in an enum?

Possible Duplicate:
How do I enumerate an enum?

Suppose there is an enum

public enum Numbers {one, two, three };

What do I have to write instead of the three dots in the following code in order to get output "one", "two", "three":

foreach (Numbers n in ...) {
   Console.WriteLine (n.ToString ());
}

Of course, I would like to do it in a way such that modifying the enum definition does not require modification of the code within the foreach ( ).


你可以使用:

foreach (Numbers n in Enum.GetValues(typeof(Numbers))) 
{
    Console.WriteLine(n.ToString());
}

If you only need to get the names you can use this:

foreach (string name in Enum.GetNames(typeof(Numbers)))
{
    Console.WriteLine(name);
}

Of course if you want to actually use the Enum values, others have pointed out already.


使用这个: Enum.GetValues(type)

链接地址: http://www.djcxy.com/p/16300.html

上一篇: 如何迭代枚举?

下一篇: 我如何列举枚举中的所有内容?