枚举的类型

本文关键字:类型 枚举 | 更新日期: 2023-09-27 17:57:06

我正在尝试从此方法制作一个通用方法:

public static SelectList LanguagesToSelectList()
{
   return new SelectList(
        Enum.GetValues(typeof(Languages))
        .Cast<Languages>()
        .Select(g => new KeyValuePair<Languages, string>(
            g,
            Resources.Views_GamesAndApplications.ResourceManager.GetString("Language_" + g.ToString()
            )
        )), 
        "Key", 
        "Value"
        );
}  

这是我得到的:

public static SelectList ToSelectList(Enum enumType, ResourceManager resourceManager, string resourcePrefix)
{
    return new SelectList(
        Enum.GetValues(typeof(enumType))
        .Cast<enumType>()
        .Select(g => new KeyValuePair<enumType, string>(
            g,
            resourceManager.GetString(resourcePrefix + g.ToString())
            )), 
        "Key", 
        "Value");
} 

但是,enumType 不应该是 Enum 型(也不应该是 Type 型),我无法弄清楚应该是什么类型,或者我是否应该改写整个方法。

使用示例(符合给定的答案):

@Html.DropDownListFor(
    m => m.Language,  
    SelectListHelper.ToSelectList<Languages>   
      (Resources.Views_GamesAndApplications.ResourceManager,"Language_"))

谢谢。

枚举的类型

public static SelectList ToSelectList<T>(ResourceManager resourceManager, string resourcePrefix)
    where T : struct 
{
    return new SelectList(Enum.GetValues(typeof(T)).Cast<T>()
                .Select(g => new KeyValuePair<T, string>(g, resourceManager.GetString(resourcePrefix + g.ToString()))), "Key", "Value");
}  
//Example:
var list = ToSelectList<Languages>(someResourceManager, "somePrefix");