无法将'TEnum'类型转换为'int'

zoa*_*oaz 3 c# linq enums

我正在尝试将枚举转换为List,如例所示,例如

Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().Select(v => new SelectListItem {
    Text = v.ToString(),
    Value = ((int)v).ToString()
}).ToList();
Run Code Online (Sandbox Code Playgroud)

这项工作,但我想修改它以使用通用枚举

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();
 }
Run Code Online (Sandbox Code Playgroud)

但是上面的代码没有编译和给出

无法将'TEnum'类型转换为'int'

为线

  Value = ((int)v).ToString()
Run Code Online (Sandbox Code Playgroud)
  1. 我如何修复上面的代码.

  2. 为什么它使用泛型枚举而不是普通枚举给出编译错误


编辑:我已经尝试了线程中的建议,但我得到了进一步的错误:

这是我的完整代码:

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();

}
Run Code Online (Sandbox Code Playgroud)

但是我遇到了运行时错误

ArgumentException:提供的类型必须是Enum.

参数名称:enumType

在线上

return Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Select(v => new SelectListItem
    {
        Text = v.ToString(),
        Value = Convert.ToInt32(v).ToString()
    }).ToList();
Run Code Online (Sandbox Code Playgroud)

我需要在代码中修复什么才能获得运行时错误.

小智 5

你没有告诉编译器TEnum.就其而言,它可以是字符串,DateTime,BankAccount,Bullet或任何东西.

要使其工作,您可以使用Enum.ParseConvert.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);
}
Run Code Online (Sandbox Code Playgroud)