枚举到字典
我想实现扩展方法,它将枚举转换为字典。
public static Dictionary ToDictionary(this Enum @enum) { Type type1 = @enum.GetType(); return Enum.GetValues(type1).Cast() //.OfType() .ToDictionary(e => Enum.GetName(@enum.GetType(), e)); }
为什么不编译?
一个错误
“找不到类型或命名空间名称’type1’(您是否缺少using指令或程序集引用?)”
Jon Skeet写了你需要的一切 ;)
但是这里有你的代码正常工作:
public static Dictionary ToDictionary(this Enum @enum) { var type = @enum.GetType(); return Enum.GetValues(type).Cast().ToDictionary(e => e, e => Enum.GetName(type, e)); }
好吧,您正在尝试使用Type
的变量作为generics类型参数。 你不能用generics来做,这是关于编译时类型的。
你可以用reflection来做,但最好将它作为通用方法。 不幸的是,你不能将generics类型参数限制为枚举,尽管我在Unconstrained Melody中有一些解决方法。
如果做不到这一点,你可以只使用struct
类型约束来获得通用方法,这将是一个良好的开端。
现在,下一个问题是您正在尝试获取Dictionary
– 但枚举的值不是 int
值。 它们可能可以转换为int
值,但它们不会立即存在。 您可以使用Convert.ToInt32
来执行此操作,但您必须执行某些操作 。
最后(暂时)你会期望使用uint
或long
底层类型的枚举发生什么?
您不能将type1用作通用参数,因为它是变量,而不是类型。
以下代码与您的代码显示的内容类似 :
public static Dictionary ToDictionary() where TEnum : struct { if (!typeof(TEnum).IsEnum) throw new ArgumentException("Type must be an enumeration"); return Enum.GetValues(typeof(TEnum)).Cast (). ToDictionary(e => Enum.GetName(typeof(TEnum), e)); }
像这样用它:
ToDictionary()
但我不确定,这是,你所期待的?
此外,它有一个问题:您可以传递任何结构,而不仅仅是枚举,这将导致运行时exception。 有关详细信息,请参阅Jon的答案。
基于Daniel的解决方案
public static SelectList ToSelectList(this HtmlHelper h) where TEnum : struct { return new SelectList(FortunaExtension.ToDictionary (), "Key", "Value"); }
这是我用来转换枚举的扩展方法,唯一不同的是我为了我的目的而返回IEnumerbale>:
public static IEnumerable> ToListOfKeyValuePairs(this TEnum enumeration) where TEnum : struct { return from TEnum e in Enum.GetValues(typeof(TEnum)) select new KeyValuePair ( (int)Enum.Parse(typeof(TEnum), e.ToString()), Regex.Replace(e.ToString(), "[AZ]", x => string.Concat(" ", x.Value[0])).Trim() ); }
它还为Value增加了空间。
例:
enum Province { BritishColumbia = 0, Ontario = 1 }
用法:
输出:
虽然@Paul Ruane是正确的,但我发现这是一个非常有用的扩展方法。 这不是一个完美的世界。