如何获取枚举列表的枚举描述? [英] How to get string list of Enum descriptions?

查看:158
本文介绍了如何获取枚举列表的枚举描述?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

枚举ToString

如何获取枚举值的列表?

How can I get a List of an Enum's values?

例如,我有以下内容:

public enum ContactSubjects
{
    [Description("General Question")]
    General,
    [Description("Availability/Reservation")]
    Reservation,
    [Description("Other Issue")]
    Other
}

我需要能够do通过ContactSubject.General作为参数,并返回描述列表。

What I need to be able to do is pass ContactSubject.General as an argument and it returns the List of the descriptions.

此方法需要使用任何枚举,而不仅仅是ContactSubject(在我的示例中) 。签名应该像GetEnumDescriptions(枚举值)一样。

This method needs to work with any Enum, not just ContactSubject (in my example). The signature should be something like GetEnumDescriptions(Enum value).

推荐答案

这样的事情可能会起作用:

Something like that may work:

    private static IEnumerable<string> GetDescriptions(Type type)
    {
        var descs = new List<string>();
        var names = Enum.GetNames(type);
        foreach (var name in names)
        {
            var field = type.GetField(name);
            var fds = field.GetCustomAttributes(typeof(DescriptionAttribute), true);
            foreach (DescriptionAttribute fd in fds)
            {
                descs.Add(fd.Description);
            }
        }
        return descs;
    }

然而,您可以查看一些逻辑,例如可以开始名字呢?你将如何处理多个描述属性?如果他们中有些人失踪了 - 你想要一个名字还是像上面那样跳过呢?等等。

however you may review some logic there: such as is it ok to start of names? how are you going to handle multiple Description attributes? What if some of them are missing - do you want a name or just skip it like above? etc.

刚刚审查过您的问题。对于VALUE,你会有这样的东西:

just reviewed your question. For the VALUE you would have something like that:

private static IEnumerable<string> GetDescriptions(Enum value)
{
    var descs = new List<string>();
    var type = value.GetType();
    var name = Enum.GetName(type, value);
    var field = type.GetField(name);
    var fds = field.GetCustomAttributes(typeof(DescriptionAttribute), true);
    foreach (DescriptionAttribute fd in fds)
    {
        descs.Add(fd.Description);
    }
    return descs;
}

然而,不可能在单个字段上放置两个描述属性,所以我猜测它可能只返回字符串。

however it is not possible to place two Description attributes on single field, so I guess it may return just string.

这篇关于如何获取枚举列表的枚举描述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆