我正在尝试将枚举转换为列表,如 this 中所述例子 例如
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();
}
但是上面的代码无法编译并给出
Cannot convert type 'TEnum' to '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: Type provided must be an Enum.
Parameter name: enumType
在线
return Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Select(v => new SelectListItem
{
Text = v.ToString(),
Value = Convert.ToInt32(v).ToString()
}).ToList();
我需要在代码中修复什么才能避免出现运行时错误。
最佳答案
您没有告诉编译器任何有关 TEnum
的信息。就其而言,它可以是字符串、DateTime、BankAccount、Bullet 或任何东西。
要使其正常工作,您可以使用 Enum.Parse
和 Convert.ToInt32
UPD:让我从评论中格式化代码并修复 SO-copy-pasters 的编译错误 :D
public static int GetEnumIntValue<T>(T value)
where T : struct
{
Type genericType = typeof(T);
Debug.Assert(genericType.IsEnum);
Enum enumValue = Enum.Parse(genericType, value.ToString()) as Enum;
return Convert.ToInt32(enumValue);
}
关于c# - 无法将类型 'TEnum' 转换为 'int',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33755630/