我想实现扩展方法,它将枚举转换为字典.
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));
}
Run Code Online (Sandbox Code Playgroud)
为什么不编译?
一个错误
"找不到类型或命名空间名称'type1'(您是否缺少using指令或程序集引用?)"
Raf*_*jer 53
但是这里有你的代码正常工作:
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));
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 13
好吧,您正在尝试使用类型变量Type作为泛型类型参数.你不能用泛型来做,这是关于编译时类型的.
你可以用反射来做,但最好将它作为通用方法.不幸的是你不能将泛型类型参数限制为枚举,尽管我在Unconstrained Melody中有一些解决方法.
如果做不到这一点,你可以只使用一个struct类型约束来进行通用方法,这将是一个良好的开端.
现在,下一个问题是你试图得到一个Dictionary<int, string>- 但是枚举的 int值不是值.它们可以转换为int值,但它们不会立即转换.你可以Convert.ToInt32用来做,但你必须做点什么.
最后(暂时)你期望使用一个uint或long底层类型的枚举发生什么?
您不能将type1用作通用参数,因为它是变量,而不是类型.
以下代码与您的代码显示的内容类似:
public static Dictionary<string, TEnum> ToDictionary<TEnum>()
where TEnum : struct
{
if (!typeof(TEnum).IsEnum)
throw new ArgumentException("Type must be an enumeration");
return Enum.GetValues(typeof(TEnum)).Cast<TEnum>().
ToDictionary(e => Enum.GetName(typeof(TEnum), e));
}
Run Code Online (Sandbox Code Playgroud)
像这样使用它:
ToDictionary<Colors>()
Run Code Online (Sandbox Code Playgroud)
但我不确定,这是,你的期望是什么?
此外,它有一个问题:您可以传递任何结构,而不仅仅是枚举,这将导致运行时异常.有关详细信息,请参阅Jon的答案.