简体   繁体   English

遍历自定义枚举的属性

[英]Iterate through properties of a custom enum

Is it possible to iterate through properties of a custom enum? 是否可以遍历自定义枚举的属性?

My custom enum looks like this: 我的自定义枚举看起来像这样:

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;
    }

I use it to enable an enum to "enumerate" with strings ie "xx", "xy"... 我使用它来使枚举可以用字符串“ xx”,“ xy”“枚举” ...

My question is if it is possible to iterate though all sexes with the goal to fill a DropDownList ListItems with value and description. 我的问题是,是否可以迭代所有性别,以用值和描述填充DropDownList ListItems为目标。

var ddlSex = new DropDownList()

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

My idea is to solve the problem with the System.Reflection library but I'm sure how. 我的想法是使用System.Reflection库解决问题,但我确定如何解决。

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());
}

When you use reflection, you should try to do it in one hit: usually in a static constructor. 当使用反射时,您应该尝试一击即可:通常是在静态构造函数中。

Here, you could do this: 在这里,您可以这样做:

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");

    ...
}

Then you can just use Sex.All , and the reflection will only happen once in your runtime. 然后,您可以只使用Sex.All ,并且反射仅在运行时发生一次。 Your invocation will look like this: 您的调用将如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM