有没有办法迭代所有枚举值?

vIc*_*erg 27 c# enumeration

可能重复:
C#:如何枚举枚举?

主题说全部.我想用它来在组合框中添加枚举的值.

谢谢

vIceBerg

alb*_*ein 26

string[] names = Enum.GetNames (typeof(MyEnum));
Run Code Online (Sandbox Code Playgroud)

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


Ray*_*yes 25

我知道其他人已经回答了正确的答案,但是,如果你想在组合框中使用枚举,你可能想要额外的码数并将字符串关联到枚举,这样你就可以提供更多细节.显示的字符串(例如使用与您的编码标准不匹配的单词或显示字符串之间的空格)

此博客条目可能很有用 - 将字符串与c#中的枚举相关联

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

作为奖励,他还提供了一种实用程序方法,用于枚举我现在使用Jon Skeet的评论更新的枚举

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;
}
Run Code Online (Sandbox Code Playgroud)

乔恩还指出,在C#3.0中它可以简化为类似的东西(现在它变得如此轻盈,我想你可以在线进行):

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>();
Run Code Online (Sandbox Code Playgroud)


ang*_*son 10

使用Enum.GetValues方法:

foreach (TestEnum en in Enum.GetValues(typeof(TestEnum)))
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

您不需要将它们转换为字符串,这样您就可以通过直接将SelectedItem属性转换为TestEnum值来检索它们.


Fir*_*aad 5

您可以迭代Enum.GetNames方法返回的数组.

public class GetNamesTest {
    enum Colors { Red, Green, Blue, Yellow };
    enum Styles { Plaid, Striped, Tartan, Corduroy };

    public static void Main() {

        Console.WriteLine("The values of the Colors Enum are:");
        foreach(string s in Enum.GetNames(typeof(Colors)))
            Console.WriteLine(s);

        Console.WriteLine();

        Console.WriteLine("The values of the Styles Enum are:");
        foreach(string s in Enum.GetNames(typeof(Styles)))
            Console.WriteLine(s);
    }
}
Run Code Online (Sandbox Code Playgroud)


rsl*_*ite 5

如果您需要组合的值与枚举的值相对应,您也可以使用如下内容:

foreach (TheEnum value in Enum.GetValues(typeof(TheEnum)))
    dropDown.Items.Add(new ListItem(
        value.ToString(), ((int)value).ToString()
    );
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以在下拉列表中显示文本并获取值(在 SelectedValue 属性中)