枚举的类型

时间:2013-02-03 07:49:02

标签: c# enums

我正在尝试使用此方法制作通用方法:

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_"))

感谢。

1 个答案:

答案 0 :(得分:3)

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