将枚举集转换为字典给定类型

Wil*_*ill 2 .net c# enums

我正在寻找创建一个将Enum转换为字典列表的函数.Enum名称也将转换为更易于阅读的形式.我想只是调用函数,提供枚举类型,然后返回字典.我相信我几乎在那里我似乎无法弄清楚如何将枚举转换为正确的类型.(在'returnList.Add'行上获得错误).现在我只是使用var作为类型,但是我知道它的类型,因为它传入了.

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;
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*kiy 5

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

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));
}
Run Code Online (Sandbox Code Playgroud)

您可以根据需要随意修改默认枚举名称.用法:

var daysDictionary = Extensions.GetEnumList<DayOfWeek>();
string monday = daysDictionary[1];
Run Code Online (Sandbox Code Playgroud)

  • @MarcinJuraszek`T`是一个类型,但你应该有类型的实例与`is`运算符一起使用它 (2认同)