【发布时间】:2018-04-18 16:38:59
【问题描述】:
我的代码中有以下两种方法,它们基本上将枚举转换为整数和字符串的字典:
public Dictionary<int, string> GetChannelLevels()
{
IEnumerable<ChannelLevel> enumValues = Enum.GetValues(typeof(ChannelLevel)).Cast<ChannelLevel>();
var channelLevels = enumValues.ToDictionary(value => (int)value, value => value.ToString());
return channelLevels;
}
public Dictionary<int, string> GetCategoryLevels()
{
IEnumerable<CategoryLevel> enumValues = Enum.GetValues(typeof(CategoryLevel)).Cast<CategoryLevel>();
var channelLevels = enumValues.ToDictionary(value => (int)value, value => value.ToString());
return channelLevels;
}
由于这两个方法的代码基本相同,所以我想写一个通用方法,看起来像这样:
private Dictionary<int, string> GetEnumDictionary<T>() where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T must be an enumerated type");
}
IEnumerable<T> enumValues = Enum.GetValues(typeof(T)).Cast<T>();
var channelLevels = enumValues.ToDictionary(value => /*THIS IS WHERE THE PROBLEM IS*/ (int)value, value => value.ToString());
return channelLevels;
}
问题在于,由于 C# 没有通用枚举包含该方法无法将 T 识别为枚举,因此我无法转换为 int。
如何在不完全编写新函数的情况下解决这个问题?
【问题讨论】:
-
当你最终 casting 时,为什么你想要一个泛型方法?在任何情况下,所有枚举都是System.Enum 类型的实例
-
@JamesThorpe 感谢您的链接。我想我可以通过这种方式实现功能来解决问题
-
@ShaiAharoni 阅读一些答案 - 其中之一就是您想要的确切通用函数。
-
基本上,您只需将
(int)value替换为Convert.ToInt32(value)即可修复您的尝试
标签: c#