2013-02-03 2 views
0

열거의 유형 : 여기나는이 방법에서 일반적인 방법을 만들려고 노력하고있어

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

감사합니다.

답변

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

이 메서드를 호출하는 방법에 대한 간단한 예제를 추가 할 수 있습니까? 즉, [T가 enum임을 보장하기위한 제약 조건]을 추가해야합니다 (http://stackoverflow.com/a/1409873/588868). –

+0

생성 된 목록을 반환해야합니다 (Asker가 잊어 버렸음을 알고 있습니다). 왜 그들이 Enum.GetValues의 일반적인 버전을 만들지는 모르겠다. '.Cast ()'대신에'((T [] Enum.GetValues ​​(typeof (T)))''(또는'KeyValuePair <,>'를 생성 할 때 unbox 만 가능합니다. –

관련 문제