I tried to catch the best of both worlds:
So I solved the problem as follows:
From lambuja a static method to return the resource of all items.
namespace SeuNamespace
{
public class Enumeration
{
public enum MeuEnum
{
[LocalizedEnum("DISPLAY_ITEM1", ResourceType = typeof(Resources))]
Item1 = 4,
[LocalizedEnum("DISPLAY_ITEM2", ResourceType = typeof(Resources))]
Item2 = 3,
[LocalizedEnum("DISPLAY_ITEM3", ResourceType = typeof(Resources))]
Item3 = 2
}
public static List<string> GetAllEnumDescription()
{
List<string> resultado = new List<string>();
foreach (MeuEnum value in Enum.GetValues(typeof(MeuEnum)))
{
FieldInfo fi = value.GetType().GetField(value.ToString());
LocalizedEnumAttribute[] attributes =
(LocalizedEnumAttribute[])fi.GetCustomAttributes(typeof(LocalizedEnumAttribute), false);
if (attributes != null && attributes.Length > 0)
resultado.Add(value.GetLocalizedDescription());
else
resultado.Add(value.ToString());
}
return resultado;
}
}
#region EnumAttribute
public class LocalizedEnumAttribute : DescriptionAttribute
{
private PropertyInfo _nameProperty;
private Type _resourceType;
public LocalizedEnumAttribute(string displayNameKey)
: base(displayNameKey)
{
}
public Type ResourceType
{
get
{
return _resourceType;
}
set
{
_resourceType = value;
_nameProperty = _resourceType.GetProperty(this.Description, BindingFlags.Static | BindingFlags.Public);
}
}
public override string Description
{
get
{
if (_nameProperty == null)
{
return base.Description;
}
return (string)_nameProperty.GetValue(_nameProperty.DeclaringType, null);
}
}
}
public static class EnumExtender
{
public static string GetLocalizedDescription(this Enum @enum)
{
if (@enum == null)
return null;
string description = @enum.ToString();
FieldInfo fieldInfo = @enum.GetType().GetField(description);
DescriptionAttribute[] attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Any())
return attributes[0].Description;
return description;
}
}
#endregion
}
To get the resource of only one item, just MeuEnum.Item1.GetLocalizedDescription();
.
To get the resource of all items just: MeuEnum.GetAllEnumDescription();
.
Tested and approved. Be happy!