枚举字典 [英] Enum to dictionary
本文介绍了枚举字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想实现的扩展方法,它将枚举字典。
公共静态字典< INT,字符串> ToDictionary(此枚举@enum)
{
类型TYPE1 = @ enum.GetType();
返回Enum.GetValues(TYPE1).Cast< TYPE1>()
// OfType< typeof运算(@enum)>()
.ToDictionary(E => Enum.GetName(@ enum.GetType(),e)条);
}
为什么不能编译?
这是错误
的类型或命名空间名称TYPE1 找不到(是否缺少 使用指令或程序集 引用?)
解决方案
乔恩斯基特写你需要一切;)
但在这里,你有你的code,它是工作:
公共静态字典< INT,字符串> ToDictionary(此枚举@enum)
{
VAR类型= @ enum.GetType();
返回Enum.GetValues(类型).Cast<诠释>()ToDictionary(E => E,E => Enum.GetName(型,E));
}
I want to implement extension method, which converts enum to dictionary.
public static Dictionary<int, string> ToDictionary(this Enum @enum)
{
Type type1 = @enum.GetType();
return Enum.GetValues(type1).Cast<type1>()
//.OfType<typeof(@enum)>()
.ToDictionary(e => Enum.GetName(@enum.GetType(), e));
}
Why it doesn't compile?
An error
"The type or namespace name 'type1' could not be found (are you missing a using directive or an assembly reference?)"
解决方案
Jon Skeet has written everything you need ;)
But here you have your code that is working:
public static Dictionary<int, string> ToDictionary(this Enum @enum)
{
var type = @enum.GetType();
return Enum.GetValues(type).Cast<int>().ToDictionary(e => e, e => Enum.GetName(type, e));
}
这篇关于枚举字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文