目前,我有以下扩展名来读取枚举中的Description
属性:
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;
}
然后以我的各种形式,我有以下代码从枚举中填充组合框:
var list = Enum.GetValues(typeof(MyEnum))
.Cast<MyEnum>()
.ToDictionary(k => k, v => v.GetAttributeOfType<DescriptionAttribute>().Description)
.ToList();
cbo.DataSource = list;
cbo.DisplayMember = "Value";
cbo.ValueMember = "Key";
上面的代码工作正常。但是,我想在第二个类似于此的扩展方法中移动代码:
public static Dictionary<T, string> FromEnum<T>(this ComboBox cbo) where T: struct, IConvertible
{
var list = Enum.GetValues(typeof(T))
.Cast<T>()
.ToDictionary(k => k, v => v.GetAttributeOfType<DescriptionAttribute>().Description)
.ToList();
cbo.DataSource = list;
cbo.DisplayMember = "Value";
cbo.ValueMember = "Key";
}
但上面的代码没有编译。我收到以下错误:
无法将lambda表达式转换为&#39; System.Collections.Generic.IEqualityComparer&#39;因为它不是委托类型
和
类型或命名空间名称&#39; DescriptionAttribute&#39;找不到(你错过了使用指令或汇编引用吗?)
第二种扩展方法是否可以正常工作?
答案 0 :(得分:0)
您可以使用以下代码:
public enum SampleEnum
{
[Description("Some Value")]
First = 1,
[Description("Some Value")]
Second = 2,
[Description("Some Value")]
Third = 3,
}
public static IList<ListItem> ToSelectList<T>(this Enum @enum, string firstOption = null)
{
var items = Enum.GetValues(typeof(T)).Cast<T>().ToList<T>();
var list = items.Select(x => new ListItem() { Text = Enum.Parse(typeof(T), x.ToString()).GetDescription(), Value = x.ToString() }).ToList();
if (firstOption != null)
{
list.Insert(0, new ListItem() { Text = firstOption, Value = "" });
}
return list;
}
并像这样使用:
SampleEnum.First.ToSelectList();
<强> UPDATING 强>
抱歉,我忘记了GetDescrption扩展程序:
public static string GetDescription(this object obj)
{
var fi = obj.GetType().GetField(obj.ToString());
var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
return attributes[0].Description;
return obj.ToString();
}