在某些情况下,您可能想向枚举值添加附加描述,例如,当枚举值本身的可读性低于您想要向用户显示的内容时。在这种情况下,您可以使用System.ComponentModel.DescriptionAttribute该类。
例如:
public enum PossibleResults
{
[Description("Success")]
OK = 1,
[Description("File not found")]
FileNotFound = 2,
[Description("Access denied")]
AccessDenied = 3
}现在,如果您想返回特定枚举值的描述,则可以执行以下操作:
public static string GetDescriptionAttribute(PossibleResults result)
{
return ((DescriptionAttribute)Attribute.GetCustomAttribute((result.GetType().GetField(result.ToString())), typeof(DescriptionAttribute))).Description;
}
static void Main(string[] args)
{
PossibleResults result = PossibleResults.FileNotFound;
Console.WriteLine(result); // Prints "FileNotFound"
Console.WriteLine(GetDescriptionAttribute(result)); // Prints "File not found"
}也可以很容易地将其转换为所有枚举的扩展方法:
static class EnumExtensions
{
public static string GetDescription(this Enum enumValue)
{
return ((DescriptionAttribute)Attribute.GetCustomAttribute((enumValue.GetType().GetField(enumValue.ToString())), typeof(DescriptionAttribute))).Description;
}
}然后像这样容易使用:Console.WriteLine(result.GetDescription());