Is there a way to iterate through all enum values?

Possible Duplicate:
C#: How to enumerate an enum?

The subject says all. I want to use that to add the values of an enum in a combobox.

Thanks

vIceBerg


string[] names = Enum.GetNames (typeof(MyEnum));

然后只需使用数组填充下拉列表


I know others have already answered with a correct answer, however, if you're wanting to use the enumerations in a combo box, you may want to go the extra yard and associate strings to the enum so that you can provide more detail in the displayed string (such as spaces between words or display strings using casing that doesn't match your coding standards)

This blog entry may be useful - Associating Strings with enums in c#

public enum States
{
    California,
    [Description("New Mexico")]
    NewMexico,
    [Description("New York")]
    NewYork,
    [Description("South Carolina")]
    SouthCarolina,
    Tennessee,
    Washington
}

As a bonus, he also supplied a utility method for enumerating the enumeration that I've now updated with Jon Skeet's comments

public static IEnumerable<T> EnumToList<T>()
    where T : struct
{
    Type enumType = typeof(T);

    // Can't use generic type constraints on value types,
    // so have to do check like this
    if (enumType.BaseType != typeof(Enum))
        throw new ArgumentException("T must be of type System.Enum");

    Array enumValArray = Enum.GetValues(enumType);
    List<T> enumValList = new List<T>();

    foreach (T val in enumValArray)
    {
        enumValList.Add(val.ToString());
    }

    return enumValList;
}

Jon also pointed out that in C# 3.0 it can be simplified to something like this (which is now getting so light-weight that I'd imagine you could just do it in-line):

public static IEnumerable<T> EnumToList<T>()
    where T : struct
{
    return Enum.GetValues(typeof(T)).Cast<T>();
}

// Using above method
statesComboBox.Items = EnumToList<States>();

// Inline
statesComboBox.Items = Enum.GetValues(typeof(States)).Cast<States>();

Use the Enum.GetValues method:

foreach (TestEnum en in Enum.GetValues(typeof(TestEnum)))
{
    ...
}

You don't need to cast them to a string, and that way you can just retrieve them back by casting the SelectedItem property to a TestEnum value directly as well.

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

上一篇: 将枚举转换为列表

下一篇: 有没有办法遍历所有的枚举值?