2016-08-05 2 views
3

저는 이제 각 페이지의 상수에 대한 문화권 특정 텍스트를 정의하는 과정에있는 작은 응용 프로그램을 만들었습니다. 몇 가지 Enum DropDownLists를 사용해 왔으며 표시 할 문자열 이름의 각 Enum 값에 Display(Name="Something") 특성을 사용했습니다. 내가 [Display(Name="SomeResourceValue", ResourceType=typeof(Resources.Resources))]문화권 전용 열거 형 DisplayName 문자열을 열거 형으로 변환

나는 데 문제에 속성 값을 변경해야했다 문화를 기반으로 텍스트를 결정하기 위해 리소스 파일을 사용하고 이제

내가 소요 정적 메서드를 가지고 있다는 것입니다 문자열 DisplayName을 반환하고 Enum 형식을 제공하면 Enum 값을 반환합니다.이 형식은 리소스 파일을 소개 한 이후로는 작동하지 않습니다.

나는 다음과 같다을 개선하기 위해 노력하고있어 방법 :

//Converts Enum DisplayName attribute text to it's Enum value 
    public static T GetEnumDisplayNameValue<T>(this string name) 
    { 
     var type = typeof(T); 
     if (!type.IsEnum) 
      throw new ArgumentException(); 
     FieldInfo[] fields = type.GetFields(); 
     var field = fields 
         .SelectMany(f => f.GetCustomAttributes(
          typeof(DisplayAttribute), false), (
           f, a) => new { Field = f, Att = a }).SingleOrDefault(a => ((DisplayAttribute)a.Att) 
          .Name == name); 

     return field == null ? default(T) : (T)field.Field.GetRawConstantValue(); 
    } 

사람이 제가 매우 감사하게 될 것입니다 자원 조회 수 있도록이 문제를 개선 할 수 있다면

. 다음

답변

0

워킹 솔루션이다

public static T GetEnumDisplayNameValue<T>(this string name, CultureInfo culture) 
    { 
     var type = typeof(T); 
     if (!type.IsEnum) 
      throw new ArgumentException(); 
     FieldInfo[] fields = type.GetFields(); 

     var field = fields.SelectMany(f => f.GetCustomAttributes(typeof(DisplayAttribute), false), 
      (f, a) => new { Field = f, Att = a }) 
      .SingleOrDefault(a => Resources.ResourceManager.GetString(((DisplayAttribute)a.Att).Name, culture) == name); 

     return field == null ? default(T) : (T)field.Field.GetRawConstantValue(); 
    } 
관련 문제