C# Enum 类型的本地化
枚举类型本地化操作的简单方案,并应用到Asp.net MVC的DropdownList中。
使用:/// <summary>
/// Enum Localizable. default resouce key={Prefix}_{Enum}
/// If you ignore Prefix,will return {EnumTypeName}_{Enum} format
/// </summary>
[AttributeUsage(AttributeTargets.Enum, AllowMultiple = true, Inherited = true)]
public class LocalizableAttribute : Attribute
{
public LocalizableAttribute(Type language)
{
this.LanguageType = language;
}
public LocalizableAttribute(Type language, String prefix)
:this(language)
{
Prefix = prefix;
}
public Type LanguageType
{
get;
set;
}
public string Prefix
{
get;
set;
}
}
public static class EnumerableExtension
{
public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
{
foreach (T item in enumerable)
{
action(item);
}
}
public static string ToLocalizable(this Enum value)
{
LocalizableAttribute customAttr=(LocalizableAttribute) Attribute.GetCustomAttribute(value.GetType(), typeof(LocalizableAttribute));
ResourceManager _resources = new ResourceManager(customAttr.LanguageType);
var prefix=customAttr.Prefix;
if (string.IsNullOrEmpty(prefix))
{
prefix=value.GetType().Name;
}
string rk = String.Format("{0}_{1}",prefix,value);
string localiza=_resources.GetString(rk);
if (localiza == null)
{
return value.ToString();
}
return localiza;
}
public static IEnumerable<SelectListItem> ToSelectList(this Enum enumValue)
{
return from Enum e in Enum.GetValues(enumValue.GetType())
select new SelectListItem { Selected = e.Equals(enumValue), Text = EnumerableExtension.ToLocalizable(e), Value = e.ToString() };
}
}
[Localizable(typeof(CoreLanguage),"UesrTitle")]
public enum UserTitle
{
Mr,
Miss
}
//in view
@Html.DropDownListFor(m => m.UserTitle, Model.UserTitle.ToSelectList(), new { id = "UserTitle" })
披荆斩棘,朝自己的信仰!Go on