我正在寻找一个将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;
}
您可以使用通用方法,该方法将使用枚举值和名称创建字典:
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));
}
可以根据需要随意修改默认枚举名称。用法:
var daysDictionary = Extensions.GetEnumList<DayOfWeek>();
string monday = daysDictionary[1];
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句