我创建了这个枚举
public enum Days
{
[Display("Monday")]
Mon,
[Display("Tuesday")]
Tue,
[Display("Wednesday")]
Wed,
[Display("Thursday")]
Thu,
[Display("Friday")]
Fri,
[Display("Satrday")]
Sat,
}
我想获得字符串“Monday”。我试着这样做
Console.WriteLine(Days.mon);
但是给了我“星期一”而不是“星期一”。 星期一有没有办法获得字符串?
答案 0 :(得分:8)
我已经增强了this answer,为您提供了更全面的解决方案,并提供了更好的语义语法。
using System;
using System.ComponentModel;
public static class EnumExtensions {
// This extension method is broken out so you can use a similar pattern with
// other MetaData elements in the future. This is your base method for each.
public static T GetAttribute<T>(this Enum value) where T : Attribute {
var type = value.GetType();
var memberInfo = type.GetMember(value.ToString());
var attributes = memberInfo[0].GetCustomAttributes(typeof(T), false);
return (T)attributes[0];
}
// This method creates a specific call to the above method, requesting the
// Description MetaData attribute.
public static string ToName(this Enum value) {
var attribute = value.GetAttribute<DescriptionAttribute>();
return attribute == null ? value.ToString() : attribute.Description;
}
}
此解决方案在Enum上创建了一对扩展方法,以便您可以执行所需的操作。我稍微增强了您的Enum
代码,以使用DisplayAttribute
类System.ComponentModel.DataAnnotations
的语法。
using System.ComponentModel.DataAnnotations;
public enum Days {
[Display(Name = "Sunday")]
Sun,
[Display(Name = "Monday")]
Mon,
[Display(Name = "Tuesday")]
Tue,
[Display(Name = "Wednesday")]
Wed,
[Display(Name = "Thursday")]
Thu,
[Display(Name = "Friday")]
Fri,
[Display(Name = "Saturday")]
Sat
}
要使用上述扩展方法,您现在只需调用以下内容:
Console.WriteLine(Days.Mon.ToName());
或
var day = Days.Mon;
Console.WriteLine(day.ToName());
答案 1 :(得分:2)
var type = typeof(Days);
var memInfo = type.GetMember(Days.Mon.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof(DisplayAttribute),
false);
var description = ((DisplayAttribute)attributes[0]).Description;
与this解决方案类似。