我可以像下面这样使用枚举吗?
我可以像TeamManager,TeamLeader,SeniorDeveloper等那样做。 但我想在“团队经理”这样的词之间留出空格
public enum SoftwareEmployee
{
Team Manager = 1,
Team Leader = 2,
Senior Developer = 3,
Junior = 4
}
答案 0 :(得分:6)
不,但你可以这样做:
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
}
答案 1 :(得分:4)
不可能提供空格,因为它会产生编译错误。如果你想要它用于显示目的。然后你可以编写一个方法,在传递枚举时返回一个UI友好的字符串
类似的东西:
public string GetUIFriendlyString(SoftwareEmployee employee)
{
switch (employee):
{
case TeamLeader: return "Team Leader";
// same for the rest
}
}
或使用@Christian Hayter建议的枚举中的属性
答案 2 :(得分:1)
不,你不能,这不能编译。
你可以在单词Senior_Developer之间添加下划线,尽管你必须问自己我在编写代码还是在写一篇文章。不要误解我的代码应该清晰,但不一定要看起来像句子。
我可能想要这样做的唯一原因是您可以将其输出到UI。诸如枚举或异常之类的代码不应该放在UI中,它可能有用,但你应该使用某种映射将枚举转换为纯文本。如果您需要处理多个本地人,这将特别有用。