2016-08-05 86 views
3

我創建了一個小應用程序,現在我正在爲每個頁面上的常量定義文化特定文本。我一直在使用一些Enum DropDownLists,並且已經使用Display(Name="Something")屬性來爲每個Enum值顯示字符串名稱。將文化特定的枚舉DisplayName字符串轉換爲枚舉

現在,我使用的資源文件,以確定基於文化,我不得不改變屬性值[Display(Name="SomeResourceValue", ResourceType=typeof(Resources.Resources))]

我有問題的文字是我有這樣的需要的靜態方法字符串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(); 
    }