我也改變了我的項目本地化一些枚舉,所以,我有一類這樣的,在創建註釋枚舉:
public class LocalizedEnumAttribute : DescriptionAttribute
{
private PropertyInfo _nameProperty;
private Type _resourceType;
public LocalizedEnumAttribute(string displayNameKey)
: base(displayNameKey)
{
}
public Type NameResourceType
{
get
{
return _resourceType;
}
set
{
_resourceType = value;
_nameProperty = _resourceType.GetProperty(this.Description, BindingFlags.Static | BindingFlags.Public);
}
}
public override string Description
{
get
{
//check if nameProperty is null and return original display name value
if (_nameProperty == null)
{
return base.Description;
}
return (string)_nameProperty.GetValue(_nameProperty.DeclaringType, null);
}
}
}
我也有EnumHelper
類在我的項目中使用它來創建枚舉的字典值本地化:
public static class EnumHelper
{
// get description data annotation using RESX files when it has
public static string GetDescription(Enum @enum)
{
if (@enum == null)
return null;
string description = @enum.ToString();
try
{
FieldInfo fi = @enum.GetType().GetField(@enum.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (attributes.Any())
description = attributes[0].Description;
}
catch
{
}
return description;
}
public static IDictionary<TKey, string> GetEnumDictionary<T, TKey>()
where T : struct
{
Type t = typeof (T);
if (!t.IsEnum)
throw new InvalidOperationException("The generic type T must be an Enum type.");
var result = new Dictionary<TKey, string>();
foreach (Enum r in Enum.GetValues(t))
{
var k = Convert.ChangeType(r, typeof(TKey));
var value = (TKey)k;
result.Add(value, r.GetDescription());
}
return result;
}
}
public static class EnumExtensions
{
public static string GetDescription(this Enum @enum)
{
return EnumHelper.GetDescription(@enum);
}
}
有了這個類,你可以在你的枚舉使用:
var data = EnumHelper.GetEnumDictionary<ActivityStatus, int>();
:
public enum ActivityStatus
{
[LocalizedEnum("InProgress", NameResourceType = typeof(Resources.Messages))]
InProgress = 0,
[LocalizedEnum("Completed", NameResourceType = typeof(Resources.Messages))]
Completed = 1,
[LocalizedEnum("Freezed", NameResourceType = typeof(Resources.Messages))]
Freezed = 2,
[LocalizedEnum("NotStarted", NameResourceType = typeof(Resources.Messages))]
NotStarted = 3,
[LocalizedEnum("None", NameResourceType = typeof(Resources.Messages))]
None = 4
}
而創建的這個組合框,您可以asp.net的MVC,像這樣的控制器上使用
你可以在你的枚舉的定義上使用屬性嗎? –
Felipe,我不想在我的枚舉上有屬性,因爲枚舉是域模型的一部分。我想在UI部分以某種方式使用這些屬性。 –