【发布时间】:2016-03-24 19:14:54
【问题描述】:
我有各种枚举作为下拉列表的来源,为了提供用户友好的描述,我为每个枚举添加了一个Description 属性,然后执行以下操作:
var list = Enum.GetValues(typeof(MyEnum))
.Cast<MyEnum>()
.ToDictionary(k => k, v => v.GetAttributeOfType<DescriptionAttribute>().Description)
.ToList();
以上是重复的,因为我必须在很多地方使用它。我尝试添加一个扩展方法:
public static T GetAttributeOfType<T>(this Enum enumVal) where T : System.Attribute
{
var type = enumVal.GetType();
var memInfo = type.GetMember(enumVal.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(T), false);
return (attributes.Length > 0) ? (T)attributes[0] : null;
}
public static KeyValuePair<T, string> ToList<T>(this Enum source)
{
return Enum.GetValues(typeof(T))
.Cast<T>()
.ToDictionary(k => k, v => v.GetAttributeOfType<DescriptionAttribute>().Description)
.ToList();
}
但是,我得到了一个例外:
无法将 lambda 表达式转换为类型“System.Collections.Generic.IEqualityComparer”,因为它不是委托类型
将其用作扩展的正确方法是什么(使用上述2种方法)?
【问题讨论】:
-
是的,有可能。
-
不应该是Enum.GetValues(typeof(source))吗?
-
@Kevin 如果我这样做,我会得到一个异常:找不到命名空间名称“源”的类型。
-
第二种方法(
ToList)很奇怪。首先,它不会编译。其次,返回类型不明确——你传递一个Enum值,然后使用ToDictionary(..).ToList(),它正在创建一个列表,返回类型是单个KeyValuePair。那么它到底应该是什么 - 单个值或列表?如果它是一个列表,那么作为扩展方法会很奇怪,所以你必须传递一个枚举值来获取列表,比如MyEnum.A.ToList<MyEnum>()。很快,您是否正在寻找与帖子开头的重复代码等效的代码? -
检查这个答案也可能有用:stackoverflow.com/a/12022617/1830909
标签: c#