【发布时间】:2015-05-14 12:24:19
【问题描述】:
我正在从枚举中创建几个下拉列表。例如,午餐时间枚举的长度将添加如下下拉列表项:
foreach (LunchBreak type in Enum.GetValues(typeof(LunchBreak)))
{
items.Add(new SelectListItem()
{
Text = SiteUtilities.GetEnumDescription(type),
Value = ((int)type).ToString()
});
}
我的枚举格式为:
public enum LunchBreak : int
{
[Description("20 minutes paid")]
Paid_20 = 0,
[Description("20 minutes unpaid")]
Unpaid_20 = 1
}
有没有办法让 foreach 循环通用,这样我就可以传入typeof(LunchBreak),这样我就不必为所有其他枚举重做代码了?
我尝试将它写在我可以传入 LunchBreak 的地方,但它抱怨我使用枚举作为类型。
我尝试做一个像这里这样的扩展方法,所以我可以调用类似 LunchBreak.GetSelectListItems("Please select a lunch break...") 的东西,并查看了几个类似这样的帖子:Create Generic method constraining T to an Enum 但并没有真正了解发生了什么
扩展尝试:
public static class EnumExtensions
{
public static List<SelectListItem> GetSelectListItems<T>(string defaultValue) where T : struct, IConvertible
{
if (typeof(T).IsEnum)
{
List<SelectListItem> items = new List<SelectListItem>()
{
new SelectListItem()
{
Text = defaultValue,
Value = string.Empty
}
};
foreach (T item in Enum.GetValues(typeof(T)))
{
items.Add(new SelectListItem()
{
Text = SiteUtilities.GetEnumDescription(item), // this line fails as item is expected to be of type Enum
Value = ((int)item).ToString() // this line fails as I can't cast item as an int
});
}
return items;
}
throw new ArgumentException("T must be an enumerated type");
}
}
【问题讨论】:
标签: c# enums extension-methods