[英]Converting Culture Specific Enum DisplayName String to Enum
我已經創建了一個小應用程序,我現在正在為每個頁面上的常量定義特定於文化的文本。 我一直在使用一些Enum DropDownLists,並且已經為每個Enum值使用Display(Name="Something")
屬性來顯示字符串名稱。
現在我正在使用資源文件來確定基於文化的文本我必須將屬性值更改為[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();
}
如果有人可以幫助我改進這個以允許資源查找,我將非常感激。
工作方案如下:
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.