您不能将枚举值分配给开头的字符串。您必须致电ToString(),这会将Country.UnitedKingdom 转换为“UnitedKingdom”。
两个选项建议自己:
- 创建
Dictionary<Country, string>
- switch 语句
- 用属性装饰每个值,并用反射加载它
对他们每个人的评论......
Dictionary<Country,string> 的示例代码
using System;
using System.Collections.Generic;
enum Country
{
UnitedKingdom,
UnitedStates,
France,
Portugal
}
class Test
{
static readonly Dictionary<Country, string> CountryNames =
new Dictionary<Country, string>
{
{ Country.UnitedKingdom, "UK" },
{ Country.UnitedStates, "US" },
};
static string ConvertCountry(Country country)
{
string name;
return (CountryNames.TryGetValue(country, out name))
? name : country.ToString();
}
static void Main()
{
Console.WriteLine(ConvertCountry(Country.UnitedKingdom));
Console.WriteLine(ConvertCountry(Country.UnitedStates));
Console.WriteLine(ConvertCountry(Country.France));
}
}
您可能希望将ConvertCountry 的逻辑放入扩展方法中。例如:
// Put this in a non-nested static class
public static string ToBriefName(this Country country)
{
string name;
return (CountryNames.TryGetValue(country, out name))
? name : country.ToString();
}
那么你可以写:
string x = Country.UnitedKingdom.ToBriefName();
如 cmets 中所述,默认的字典比较器将涉及装箱,这是不理想的。对于一次性的,我会忍受它,直到我发现它是一个瓶颈。如果我对多个枚举执行此操作,我会编写一个可重用的类。
切换语句
我同意yshuditelu's answer 建议在相对较少的情况下使用switch 语句。但是,由于每个案例都将是一个单独的语句,因此我会针对这种情况亲自更改我的编码风格,以保持代码紧凑但可读:
public static string ToBriefName(this Country country)
{
switch (country)
{
case Country.UnitedKingdom: return "UK";
case Country.UnitedStates: return "US";
default: return country.ToString();
}
}
您可以在其中添加更多案例而不会变得太大,并且很容易将您的目光从枚举值转移到返回值。
DescriptionAttribute
Rado made 关于DescriptionAttribute 的代码可重用的观点很好,但在这种情况下,我建议不要在每次需要获取值时都使用反射。我可能会编写一个通用静态类来保存一个查找表(可能是Dictionary,可能带有 cmets 中提到的自定义比较器)。扩展方法不能在泛型类中定义,所以你最终可能会得到类似的东西:
public static class EnumExtensions
{
public static string ToDescription<T>(this T value) where T : struct
{
return DescriptionLookup<T>.GetDescription(value);
}
private static class DescriptionLookup<T> where T : struct
{
static readonly Dictionary<T, string> Descriptions;
static DescriptionLookup()
{
// Initialize Descriptions here, and probably check
// that T is an enum
}
internal static string GetDescription(T value)
{
string description;
return Descriptions.TryGetValue(value, out description)
? description : value.ToString();
}
}
}