我正在寻找创建一个将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;
}
答案 0 :(得分: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));
}
您可以根据需要随意修改默认枚举名称。用法:
var daysDictionary = Extensions.GetEnumList<DayOfWeek>();
string monday = daysDictionary[1];
答案 1 :(得分:4)
有一段时间是使用enum和描述的更好方法,并通过泛型方法获得Dictonary(EnumValue,EnumValueDescription)。我在下拉列表中需要视图过滤器时使用它。 您可以将它用于您的代码中的任何枚举。
例如:
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());
}
}
电话看起来像这样:
public static class SomeFilters
{
public static Dictionary<SomeUserFilter, string> UserFilters = EnumExtensions.EnumToDictionary<SomeUserFilter>();
}
对于枚举:
public enum SomeUserFilter
{
[Description("Active")]
Active = 0,
[Description("Passive")]
Passive = 1,
[Description("Active & Passive")]
All = 2
}
答案 2 :(得分:1)
请注意,在C#中使用enum定义的类型可以有各种基础类型(byte,sbyte,short,ushort,int,uint,long,ulong),如文档所述:enum。这意味着并非所有枚举值都可以安全地转换为int并且在没有抛出异常的情况下逃脱。
例如,如果您希望概括一下,可以安全地将所有枚举值强制转换为浮点数(尽管奇数,它涵盖了Implicit Numeric Conversions Table告诉的任何枚举基础类型)。或者您可以通过泛型请求特定的基础类型。
两种解决方案都不是完美的,尽管通过适当的参数验证可以安全地完成工作。泛化浮点值解决方案:
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");
}
通用参数解决方案:
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键的字典是带有提供的枚举值enum的底层类型是char,应该没有问题,因为在int上存储char没有问题。