不,但您可以这样做:
public enum SoftwareEmployee {
[Description("Team Manager")] TeamManager = 1,
[Description("Team Leader")] TeamLeader = 2,
[Description("Senior Developer")] SeniorDeveloper = 3,
[Description("Junior")] Junior = 4
}
然后您可以使用实用方法将枚举值转换为描述,例如:
/// <summary>
/// Given an enum value, if a <see cref="DescriptionAttribute"/> attribute has been defined on it, then return that.
/// Otherwise return the enum name.
/// </summary>
/// <typeparam name="T">Enum type to look in</typeparam>
/// <param name="value">Enum value</param>
/// <returns>Description or name</returns>
public static string ToDescription<T>(this T value) where T : struct {
if(!typeof(T).IsEnum) {
throw new ArgumentException(Properties.Resources.TypeIsNotAnEnum, "T");
}
var fieldName = Enum.GetName(typeof(T), value);
if(fieldName == null) {
return string.Empty;
}
var fieldInfo = typeof(T).GetField(fieldName, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Static);
if(fieldInfo == null) {
return string.Empty;
}
var descriptionAttribute = (DescriptionAttribute) fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false).FirstOrDefault();
if(descriptionAttribute == null) {
return fieldInfo.Name;
}
return descriptionAttribute.Description;
}
我更喜欢通过 switch 手动翻译,因为如果所有内容都在一起,维护枚举定义会更容易。
要允许描述文本的本地化,请使用从资源中获取其值的不同描述属性,例如ResourceDescription。只要它继承自Description,就可以正常工作。例如:
public enum SoftwareEmployee {
[ResourceDescription(typeof(SoftwareEmployee), Properties.Resources.TeamManager)] TeamManager = 1,
[ResourceDescription(typeof(SoftwareEmployee), Properties.Resources.TeamLeader)] TeamLeader = 2,
[ResourceDescription(typeof(SoftwareEmployee), Properties.Resources.SeniorDeveloper)] SeniorDeveloper = 3,
[ResourceDescription(typeof(SoftwareEmployee), Properties.Resources.Junior)] Junior = 4
}