首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将Enum集合转换为给定类型的字典

将Enum集合转换为给定类型的字典
EN

Stack Overflow用户
提问于 2013-09-17 16:40:45
回答 3查看 6.3K关注 0票数 2

我希望创建一个将Enum转换为字典列表的函数。Enum名称也将被转换成一种更具人类可读性的形式。我只想调用这个函数,提供枚举类型,然后把字典拿回来。我相信我就快到了,我只是想不出该如何把精气投给正确的类型。(在“returnList.Add”行上出现错误)。现在,我只是使用var作为类型,但是我知道类型,因为它已经传入。

代码语言:javascript
运行
复制
internal static Dictionary<int,string> GetEnumList(Type e)
{
    List<string> exclusionList =
    new List<string> {"exclude"};

    Dictionary<int,string> returnList = new Dictionary<int, string>();

    foreach (var en in Enum.GetValues(e))
    {
        // split if necessary
        string[] textArray = en.ToString().Split('_');

        for (int i=0; i< textArray.Length; i++)
        {
            // if not in the exclusion list
            if (!exclusionList
                .Any(x => x.Equals(textArray[i],
                    StringComparison.OrdinalIgnoreCase)))
            {
                textArray[i] = Thread.CurrentThread.CurrentCulture.TextInfo
                    .ToTitleCase(textArray[i].ToLower());
            }
        }

        returnList.Add((int)en, String.Join(" ", textArray));
    }

    return returnList;
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-09-17 16:48:07

您可以使用泛型方法,它将创建具有枚举值和名称的字典:

代码语言:javascript
运行
复制
public static Dictionary<int, string> GetEnumList<T>()
{
    Type enumType = typeof(T);
    if (!enumType.IsEnum)
        throw new Exception("Type parameter should be of enum type");

    return Enum.GetValues(enumType).Cast<int>()
               .ToDictionary(v => v, v => Enum.GetName(enumType, v));
}

您可以随意修改默认枚举名称。用法:

代码语言:javascript
运行
复制
var daysDictionary = Extensions.GetEnumList<DayOfWeek>();
string monday = daysDictionary[1];
票数 6
EN

Stack Overflow用户

发布于 2014-05-16 19:29:49

一些时间是使用枚举和描述的较好方式,并通过泛型方法获得Dictonary(EnumValue,EnumValueDescription)。我使用它时,我需要视图过滤器在下拉。您可以在代码中的任何枚举中使用它。

例如:

代码语言:javascript
运行
复制
public static class EnumExtensions
{
    public static string GetDescription(this Enum value)
    {
        Type type = value.GetType();
        string name = Enum.GetName(type, value);
        if (name != null)
        {
            FieldInfo field = type.GetField(name);
            if (field != null)
            {
                var attr = Attribute.GetCustomAttribute(field, typeof (DescriptionAttribute)) as DescriptionAttribute;
                if (attr != null)
                {
                    return attr.Description;
                }
            }
        }
        return value.ToString();
    }

    public static Dictionary<T, string> EnumToDictionary<T>()
    {
        var enumType = typeof(T);

        if (!enumType.IsEnum)
            throw new ArgumentException("T must be of type System.Enum");

        return Enum.GetValues(enumType)
                   .Cast<T>()
                   .ToDictionary(k => k, v => (v as Enum).GetDescription());
    }
}

电话看起来是这样的:

代码语言:javascript
运行
复制
public static class SomeFilters
{
    public static Dictionary<SomeUserFilter, string> UserFilters = EnumExtensions.EnumToDictionary<SomeUserFilter>();
}

用于枚举:

代码语言:javascript
运行
复制
public enum SomeUserFilter
{
    [Description("Active")]
    Active = 0,

    [Description("Passive")]
    Passive = 1,

    [Description("Active & Passive")]
    All = 2
}
票数 4
EN

Stack Overflow用户

发布于 2013-09-17 17:55:27

请注意,在C#中使用枚举定义的类型可以有多种底层类型(字节、字节、短、ushort、int、uint、long、ulong),如文档所述:枚举。这意味着,并非所有枚举值都可以安全地抛出到int中,然后在没有抛出异常的情况下离开。

例如,如果您希望泛化,您可以安全地将所有枚举值转换为浮动(虽然奇怪,但它涵盖了隐式数值转换表告诉的任何枚举底层类型)。也可以通过泛型请求特定的基础类型。

这两种解决方案都是完美的,尽管两者都通过充分的参数验证安全地完成了工作。泛化到浮点值解决方案:

代码语言:javascript
运行
复制
static public IDictionary<float, string> GetEnumList(Type enumType)
{
    if (enumType != null)
        if (enumType.IsEnum)
        {
            IDictionary<float, string> enumList = new Dictionary<float, string>();

            foreach (object enumValue in Enum.GetValues(enumType))
                enumList.Add(Convert.ToSingle(enumValue), Convert.ToString(enumValue));

            return enumList;
        }
        else
            throw new ArgumentException("The provided type is not an enumeration.");
    else
        throw new ArgumentNullException("enumType");
}

通用参数解决方案:

代码语言:javascript
运行
复制
static public IDictionary<EnumUnderlyingType, string> GetEnumList<EnumUnderlyingType>(Type enumType)
{
    if (enumType != null)
        if (enumType.IsEnum && typeof(EnumUnderlyingType) == Enum.GetUnderlyingType(enumType))
        {
            IDictionary<EnumUnderlyingType, string> enumList = new Dictionary<EnumUnderlyingType, string>();

            foreach (object enumValue in Enum.GetValues(enumType))
                enumList.Add((EnumUnderlyingType)enumValue, enumValue.ToString());

            return enumList;
        }
        else
            throw new ArgumentException("The provided type is either not an enumeration or the underlying type is not the same with the provided generic parameter.");
    else
        throw new ArgumentNullException("enumType");
}

或者,您可以将其中一个与lazyberezovsky的解决方案结合使用,以避免空检查。或者更好地使用隐式转换提供的解决方案(例如,您有一个带底层类型char的枚举,您可以安全地将char转换为int,这意味着如果请求返回int键的字典,该方法是提供的枚举的枚举值,它的基础类型是char,它应该没有问题,因为在int上存储char没有问题)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18855304

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档