枚举本地化 [英] Enum localization
本文介绍了枚举本地化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何本地化 ListBoxFor
的枚举,其中可能有多个选项?
How do you localize enums for a ListBoxFor
where multiple options are possible?
例如一个包含角色的enum
:
public enum RoleType
{
[Display(Description = "Administrator", ResourceType = typeof(Resource))]
Administrator = 1,
[Display(Description = "Moderator", ResourceType = typeof(Resource))]
Moderator = 2,
[Display(Description = "Webmaster", ResourceType = typeof(Resource))]
Webmaster = 3,
[Display(Description = "Guest", ResourceType = typeof(Resource))]
Guest = 4,
Etc.... = 5,
}
我已经看到使用 dropdownlist
/selectlists
完成的.但是有没有办法为多选列表做到这一点?
I have seen this done with dropdownlist
/selectlists
. But is there a way to do this for a multi select list?
这就是我想要使用它的方式,这就是它现在的工作方式,但不会被翻译成其他语言:
This is how I'd like to use it, which is how it works now but doesn't get translated in a different language:
var roles = from role r in Enum.GetValues(typeof(RoleType))
select new
{
Id = (int)Enum.Parse(typeof(RoleType), r.ToString()),
Name = r.ToString()
};
searchModel.roles = new MultiSelectList(roles, "Id", "Name");
注意:我已将枚举从 Role 重命名为 RoleType.
Note: i have renamed the enum from Role to RoleType.
推荐答案
您可以实现一个描述属性.
You can implement a description attribute.
public class LocalizedDescriptionAttribute : DescriptionAttribute
{
private readonly string _resourceKey;
private readonly ResourceManager _resource;
public LocalizedDescriptionAttribute(string resourceKey, Type resourceType)
{
_resource = new ResourceManager(resourceType);
_resourceKey = resourceKey;
}
public override string Description
{
get
{
string displayName = _resource.GetString(_resourceKey);
return string.IsNullOrEmpty(displayName)
? string.Format("[[{0}]]", _resourceKey)
: displayName;
}
}
}
public static class EnumExtensions
{
public static string GetDescription(this Enum enumValue)
{
FieldInfo fi = enumValue.GetType().GetField(enumValue.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute),
false);
if (attributes != null &&
attributes.Length > 0)
return attributes[0].Description;
else
return enumValue.ToString();
}
}
这样定义:
public enum Roles
{
[LocalizedDescription("Administrator", typeof(Resource))]
Administrator,
...
}
并像这样使用它:
var roles = from RoleType role in Enum.GetValues(typeof(RoleType))
select new
{
Id = (int)role,
Name = role.GetDescription()
};
searchModel.roles = new MultiSelectList(roles, "Id", "Name");
这篇关于枚举本地化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文