ABP 自动本地化枚举
protected virtual List<SelectListItem> GetSelectItemsFromEnum(TagHelperContext context, TagHelperOutput output, ModelExplorer explorer)
{
var selectItems = new List<SelectListItem>();
var isNullableType = Nullable.GetUnderlyingType(explorer.ModelType) != null;
var enumType = explorer.ModelType;
if (isNullableType)
{
enumType = Nullable.GetUnderlyingType(explorer.ModelType);
selectItems.Add(new SelectListItem());
}
var containerLocalizer = _tagHelperLocalizer.GetLocalizerOrNull(explorer.Container.ModelType.Assembly);
foreach (var enumValue in enumType.GetEnumValues())
{
var memberName = enumType.GetEnumName(enumValue);
var localizedMemberName = AbpInternalLocalizationHelper.LocalizeWithFallback(
new[]
{
containerLocalizer,
_stringLocalizerFactory.CreateDefaultOrNull()
},
new[]
{
$"Enum:{enumType.Name}.{memberName}",
$"{enumType.Name}.{memberName}",
memberName
},
memberName
);
selectItems.Add(new SelectListItem
{
Value = enumValue.ToString(),
Text = localizedMemberName
});
}
return selectItems;
}
框架代码:
public static class EnumHelper
{
public static string GetLocalizedMemberName(Type enumType, object value, IStringLocalizerFactory stringLocalizerFactory)
{
var memberName = enumType.GetEnumName(value);
var localizedMemberName = AbpInternalLocalizationHelper.LocalizeWithFallback(
new[]
{
stringLocalizerFactory.CreateDefaultOrNull()
},
new[]
{
$"Enum:{enumType.Name}.{memberName}",
$"{enumType.Name}.{memberName}",
memberName
},
memberName
);
return localizedMemberName;
}
}
JSON文件格式:
{
"culture": "en",
"texts": {
"Enum:CarType.Sedan": "Sedan Car",
"Enum:CarType.Hatchback": "Hatchback Car",
"Enum:CarType.Coupe": "Coupe Car"
}
}