2016-08-05 88 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(); 
    }