我正在尝试将枚举转换为列表,如中所述this https://stackoverflow.com/questions/3489453/how-can-i-convert-an-enumeration-into-a-listselectlistitem例子
例如
Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Select(v => new SelectListItem {
Text = v.ToString(),
Value = ((int)v).ToString()
}).ToList();
这项工作有效,但我想修改它以与通用枚举一起使用
public static List<SelectListItem> GetEnumList<TEnum>(TEnum value)
{
return Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Select(v => new SelectListItem
{
Text = v.ToString(),
Value = ((int)v).ToString()
}).ToList();
}
然而上面的代码没有编译并给出
无法将类型“TEnum”转换为“int”
对于线
Value = ((int)v).ToString()
-
我该如何修复上面的代码。
-
为什么它会给出通用枚举的编译错误,而不是普通枚举的编译错误
编辑:我已经尝试了线程中的建议,但出现了进一步的错误:
这是我的完整代码:
public static IHtmlContent EnumDropDownListFor<TModel, TResult,TEnum>(
this IHtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TResult>> expression,
TEnum enumValue,
string optionLabel)
{
return htmlHelper.DropDownListFor(expression, (IEnumerable<SelectListItem>)GetEnumList(enumValue), optionLabel);
}
public static List<SelectListItem> GetEnumList<TEnum>(TEnum value)
{
return Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Select(v => new SelectListItem
{
Text = v.ToString(),
Value = Convert.ToInt32(v).ToString()
}).ToList();
}
但我收到运行时错误
ArgumentException:提供的类型必须是枚举。
参数名称:枚举类型
在线上
return Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Select(v => new SelectListItem
{
Text = v.ToString(),
Value = Convert.ToInt32(v).ToString()
}).ToList();
我需要在代码中修复什么才能避免出现运行时错误。