如何获得枚举描述字符串列表? [英] How to get string list of Enum descriptions?

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

问题描述

可能重复:结果
枚举的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
}

我需要什么才能够做的是通过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).

感谢您!

推荐答案

类似的东西可能工作:

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



不过,你可以查看一些逻辑存在:比如是不是OK开始名字呢?你打算怎么处理多个说明属性?如果他们中的一些缺少什么 - 你想要的名称或只是跳过它像上面?等等。

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天全站免登陆