Related: Get enum from enum attribute
I want the most maintainable way of binding an enumeration and it\'s associated localized string values to something.
I do mapping to resourse in the following way: 1. Define a class StringDescription with ctor getting 2 parameters (type of resourse and it's name)
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
class StringDescriptionAttribute : Attribute
{
private string _name;
public StringDescriptionAttribute(string name)
{
_name = name;
}
public StringDescriptionAttribute(Type resourseType, string name)
{
_name = new ResourceManager(resourseType).GetString(name);
}
public string Name { get { return _name; } }
}
Create a resourse file for either culture (for example WebTexts.resx and Webtexts.ru.resx). Let is be colours Red, Green, etc...
Define enum:
enum Colour{ [StringDescription(typeof(WebTexts),"Red")] Red=1 , [StringDescription(typeof(WebTexts), "Green")] Green = 2, [StringDescription(typeof(WebTexts), "Blue")] Blue = 3, [StringDescription("Antracit with mad dark circles")] AntracitWithMadDarkCircles
}
Define a static method getting resource description via reflection
public static string GetStringDescription(Enum en) {
var enumValueName = Enum.GetName(en.GetType(),en);
FieldInfo fi = en.GetType().GetField(enumValueName);
var attr = (StringDescriptionAttribute)fi.GetCustomAttribute(typeof(StringDescriptionAttribute));
return attr != null ? attr.Name : "";
}
Eat :
Colour col; col = Colour.Red; Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");
var ListOfColors = typeof(Colour).GetEnumValues().Cast().Select(p => new { Id = p, Decr = GetStringDescription(p) }).ToList();
foreach (var listentry in ListOfColors)
Debug.WriteLine(listentry.Id + " " + listentry.Decr);