如何获取Enum描述的字符串列表?
如何获得Enum值的列表?
例如,我有以下内容:
public enum ContactSubjects { [Description("General Question")] General, [Description("Availability/Reservation")] Reservation, [Description("Other Issue")] Other }
我需要做的是将ContactSubject.General作为参数传递,它返回描述的列表。
此方法需要使用任何枚举,而不仅仅是ContactSubject(在我的示例中)。 签名应该类似于GetEnumDescriptions(枚举值)。
这样的事情可能有用:
private static IEnumerable GetDescriptions(Type type) { var descs = new List (); var names = Enum.GetNames(type); foreach (var name in names) { var field = type.GetField(name); var fds = field.GetCustomAttributes(typeof(DescriptionAttribute), true); foreach (DescriptionAttribute fd in fds) { descs.Add(fd.Description); } } return descs; }
但是你可以在那里查看一些逻辑:比如可以开始名字吗? 你将如何处理多个描述属性? 如果其中一些丢失了怎么办 – 你想要一个名字还是像上面那样跳过它? 等等
刚刚回顾了你的问题。 对于VALUE,你会有类似的东西:
private static IEnumerable GetDescriptions(Enum value) { var descs = new List (); var type = value.GetType(); var name = Enum.GetName(type, value); var field = type.GetField(name); var fds = field.GetCustomAttributes(typeof(DescriptionAttribute), true); foreach (DescriptionAttribute fd in fds) { descs.Add(fd.Description); } return descs; }
但是不可能在单个字段上放置两个Description属性,所以我猜它可能只返回字符串。