迭代自定义枚举的属性

时间:2014-03-11 21:33:32

标签: c# reflection enums

是否可以迭代自定义枚举的属性?

我的自定义枚举如下所示:

public class Sex
{
    public static readonly Sex Female = new Sex("xx", "Female");

    public static readonly Sex Male = new Sex("xy", "Male");

    internal string Value { get; private set; }

    internal string Description { get; private set; }

    public override string ToString()
    {
        return Value.ToString();
    }

    public string GetDescription()
    {
        return this.Description;
    }

    protected Sex(string value, string description)
    {
        this.Value = value;
        this.Description = description;
    }

我使用它来启用枚举"枚举"带字符串,即" xx"," xy" ...

我的问题是,是否可以迭代所有性别,目标是用值和描述填充DropDownList ListItems。

var ddlSex = new DropDownList()

foreach(var sex in typeof(Sex).<some_magic>)
{
    ddlSex.Items.Add(new ListItem(sex.ToString(), sex.GetDescription()));
}

我的想法是用System.Reflection库解决问题,但我确定如何。

2 个答案:

答案 0 :(得分:3)

var list = typeof(Sex).GetFields(BindingFlags.Static | BindingFlags.Public)
            .Select(f => (Sex)f.GetValue(null))
            .ToList();

foreach(var sex in list)
{
    Console.WriteLine(sex.ToString() + ":" + sex.GetDescription());
}

答案 1 :(得分:1)

当你使用反射时,你应该尝试在一次命中中执行:通常在静态构造函数中。

在这里,您可以这样做:

public class Sex
{
    public static readonly List<Sex> All = typeof(Sex).GetFields(BindingFlags.Public | BindingFlags.Static)
        .Where(f => f.FieldType == typeof(Sex))
        .Select(f => (Sex)f.GetValue(null))
        .ToList();

    public static readonly Sex Female = new Sex("xx", "Female");

    public static readonly Sex Male = new Sex("xy", "Male");

    ...
}

然后你可以使用Sex.All,反射只会在运行时发生一次。您的调用将如下所示:

foreach(var sex in Sex.All)
{
    this.ddlSex.Items.Add(new ListItem(sex.ToString(), sex.GetDescription()));
}